JSFiddle - React, Tailwind, and code Playground
by no2don
HTML
<label for="input1">輸入框1:</label>
<input type="number" class='base' step="any">
<br>
<label for="input2">輸入框2:</label>
<input type="number" class='sync' step="any">
<br>
<label for="input2">輸入框3:</label>
<input type="number" class='sync' step="any">
<br>
<label for="input2">輸入框4:</label>
<input type="number" class='sync' step="any">
<br>
<label for="input2">輸入框5:</label>
<input type="number" class='sync' step="any">
JavaScript
$('.base').keydown(function(){
// 延遲處理,確保 input1 的值在 keydown 後已更新
setTimeout(function() {
// 檢查值是否是合理的數值(使用正則表達式)
if (/^-?\d*\.?\d*$/.test($('.base').val())) {
// 將 input1 的值同步到 input2,只有當 input2 為空或以 input1 的值開頭時
// if (input2.value.trim() === '' || input2.value.startsWith(value1)) {
$('.sync').val($('.base').val())
// }
}
}, 49);
});