gpt4 book ai didi

javascript - 如何在vanilla js中自动获取输入值?

转载 作者:行者123 更新时间:2023-12-01 00:29:41 26 4
gpt4 key购买 nike

有没有什么javascript方法可以自动获取输入文本的值?我正在使用条形码扫描仪,我想在我的文本字段获得值时触发一个事件,否则什么都不做。截至目前我正在使用,更改事件如下:

if(document.getElementById("item")){
document.getElementById("item").addEventListener("change", function(){
let item = document.getElementById("item").value;
if(item){
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "http://"+window.location.hostname+":"+window.location.port+"/api/employee/search/1/"+item);
httpRequest.send();
httpRequest.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200){
var employee = JSON.parse(httpRequest.responseText);
if(typeof(employee.id) !== 'undefined'){
console.log(employee)
urlRequest = "http://"+window.location.hostname+":"+window.location.port+"/employee/"+employee.id;
location.replace(urlRequest);
}
}
}
}
});
}

但问题是用户仍然需要按键盘中的Enter键。

最佳答案

根据MDN文档:

The input event fires when the value of an input, select, or textarea element has been changed.

您可以按如下方式使用它:

document.querySelector("#input").addEventListener("input", x => console.log(x.target.value))
<input id='input' type='text' />

关于javascript - 如何在vanilla js中自动获取输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58679713/

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