JavaScript:如何根据另一个插入的值计算和更新输入字段值



我有两个输入字段和一个变量:

var x = 5;
First: <input type="text" name="first">
Second: <input type="text" name="second">

当我在第一个输入字段中输入值时,我想更新并显示第二个输入字段值:first-input-field-value * x

当我在第二个输入字段中输入值时,我想更新并显示第一个输入字段值:x / second-input-field-value

一个简单的解决方案是实现为每个输入元素执行相应算术的事件处理程序。需要考虑的一些事项是:

  • 确保用户提供的输入是有效的数字。下面我解析更新输入的当前字符串值,并确保解析的结果是有效的数字,然后再执行 arthimetic
  • 使用input事件确保立即处理 Arthimetic 和输入更新,并针对不同的用户交互(按键、从键盘粘贴等(

在代码中,这可以写成:

/* Query document for first and second input elements */
const inputFirst = document.querySelector('input[name="first"]');
const inputSecond = document.querySelector('input[name="second"]');
const x = 5;
/* 
Add event handler for the input event that will be run when user interaction 
with input causes value change 
*/
inputFirst.addEventListener("input", (event) => {
/* Obtain current numeric value for this input after user interaction */
const value = Number.parseFloat(event.target.value);
if(!Number.isNaN(value)) {
/* 
The value is a number, so we're safe to use it for arithmetic. Here
we update the value of the secondInput from the input event of the
firstInput 
*/
inputSecond.value = value * x;
}

});
inputSecond.addEventListener("input", (event) => {

const value = Number.parseFloat(event.target.value);
if(!Number.isNaN(value)) {
inputFirst.value = value / x;
}

});
First: <input type="text" name="first">
Second: <input type="text" name="second">

最新更新