首页 > 解决方案 > 一旦有值使用 javascript 填充或在输入字段中使用键盘输入时检测

问题描述

我编写了这段代码,它检测是否productName使用 javascript 在字段中填充了值,然后解析并自动填充输入字段quantity。我的代码仅在productName通过javascript代码填充字段并且在我使用时无法注册键盘输入时才有效onChange

我想在这两种情况下检测,即 javascript 和键盘,如何在这段代码中检测使用键盘?

const input = document.getElementById('productName');

const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value');

Object.defineProperty(input, 'value', {
    set: function(t) {
        console.log('Input value was changed programmatically');
         descriptor.set.apply(this, arguments);
         document.getElementById("quantity").value=t
    },
    get: function() {
      return descriptor.get.apply(this);
    }
});

var i=0;
function changeInput(){
/* console.log(document.getElementById('productName').value) */
document.getElementById("productName").value=i++;
}
<input type="text" id="productName" name="productName"  placeholder="product name">
<input type="text" id="quantity" name="quantity" placeholder="quantity">
<button onclick="changeInput()">Change</button>

标签: javascript

解决方案


由于我是 Javascript 的初学者,@epascarello 的评论帮助了我,这很容易绑定输入元素:

 document.getElementById("productName").addEventListener("input",(event)=>{
  document.getElementById("quantity").value= document.getElementById("productName").value;
})

推荐阅读