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

标签 javascript addeventlistener

有没有什么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/

相关文章:

javascript - 在循环内使用 setTimeout 不允许阻塞

javascript - addEventListener 没有调用我的函数

javascript - 在vue中删除事件监听器

javascript - 值更改后,addeventlistener 中的变量未更新

javascript - 如何使用 .addEventListener 打印出数组的特定项?

javascript - 使用 addEventListener 附加时不调用事件

javascript - 哪种注释格式适用于带有注释的 TypeScript?

javascript - 从 JS 迁移到 TS,Jest 看不到 "globals"

javascript - SharePoint 2013 库检索所有文件名。休息API

javascript - html、css、粘盒、Chrome 的问题