首页 > 解决方案 > 在输入时检查输入字段值对 js 对象值

问题描述

我的输入框<input type="text" id="barcode" placeholder="Barcode" onkeypress="search(this)">

我想通过在我的 js 对象中按回车键来检查它的值。

function search(ele) {
    if(event.key === 'Enter') {
        // element.anr is the value i want to check my input against
        if (ele.value === element.anr) {
            // action that should be performed if value is equal
            document.getElementById("next").click();        
        }
    }
};

我在这里做错了什么?当我输入正确的值并按 Enter 键时,什么也没有发生(旁注document.getElementById("next").click();显示我的 js 对象的下一个键及其值)

标签: javascripthtml

解决方案


您可以使用eventListeners,

const node = document.getElementsById("barcode");
node.addEventListener("keydown", function(event) {
    if (event.key === "Enter") {
        event.preventDefault();
        // Do more work
    }
});

推荐阅读