我有两个输入字段和一个变量:
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
答案 0 :(得分:4)
一个简单的解决方案是实现对每个输入元素执行相应算术的事件处理程序。需要考虑的一些事情是:
input
事件可确保立即执行人工更新和输入更新,并确保针对不同的用户交互(按键,键盘粘贴等)在代码中,可以这样写:
/* 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">