模擬簡易計算機鍵盤:點擊運算子按鈕 (+, -, *, /, ...),將符號追加到 textarea 末尾,支援連續點擊累積運算式。
<!DOCTYPE html>
<html>
<head>
<meta charset="gbk">
<title>運算式輸入</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="form1">
<table class="base_table" border="1" style="border-collapse:collapse">
<tr>
<td>
<textarea id="textareaValidate" cols="75" rows="5" placeholder="點擊下方按鈕輸入運算式..."></textarea>
</td>
</tr>
<tr>
<td>
<input type="button" class="op-btn" value=" + " />
<input type="button" class="op-btn" value=" - " />
<input type="button" class="op-btn" value=" * " />
<input type="button" class="op-btn" value=" / " />
<input type="button" class="op-btn" value=" ! " />
<input type="button" class="op-btn" value=" = " />
<input type="button" class="op-btn" value=" < " />
<input type="button" class="op-btn" value=" > " />
<input type="button" class="op-btn" value=" & " />
<input type="button" class="op-btn" value=" | " />
<input type="button" class="op-btn" value=" ( " />
<input type="button" class="op-btn" value=" ) " />
</td>
</tr>
</table>
</form>
<script>
$(function() {
var $textarea = $('#textareaValidate');
// 使用類別選擇器,不依賴 ID 命名規則
$('.op-btn').on('click', function() {
var val = $.trim($(this).val()); // 取得按鈕值並去除空白
$textarea.val($textarea.val() + val); // 追加到現有內容
$textarea.focus(); // 保持焦點方便繼續輸入
});
});
</script>
</body>
</html>
$.trim() 移除按鈕值首尾空白 (HTML 中為了排版加了空格)。val(newVal) 設定 textarea 內容;val() 取得內容。$('.op-btn').on('click', ...) 可自動套用於動態新增按鈕。focus() 讓使用者可直接繼續鍵盤輸入或點擊下一按鈕。
$textarea.on('keydown', function(e) {
// 允許:數字、運算子、Backspace、Delete、方向鍵、Tab
var allowed = /^[\d+\-*/=<>!&|()\s]$/.test(e.key) ||
['Backspace','Delete','ArrowLeft','ArrowRight','Tab','Enter'].includes(e.key);
if (!allowed && !e.ctrlKey && !e.metaKey) e.preventDefault();
});
若此運算式需送後端 eval 計算,**極度危險** (任意代碼執行)。前端應僅做輸入輔助,後端需用安全表達式解析器 (如 math.js、expr-eval、自寫遞歸下降解析器) 而非 eval。