gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:39:44 24 4
gpt4 key购买 nike

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

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

最佳答案

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

  • 确保用户提供的输入是有效数字。下面我解析更新后的输入的当前字符串值,并确保解析结果是一个有效的数字,然后再执行算术
  • 使用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">

关于JavaScript:如何根据另一个输入的值计算和更新输入字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57701314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com