如何自动获取Vanilla JS中的输入值?

时间:2019-11-03 11:29:31

标签: 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

2 个答案:

答案 0 :(得分:1)

您可以使用keydown事件:

const input = document.getElementById('test')

input.addEventListener("keydown", () => {  
 console.log(input.value)
});
<input id='test' type='text' />

答案 1 :(得分:1)

根据MDN文档:

  

输入,选择或textarea元素的值已更改时,将触发input事件。

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

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