Javascript 在没有提交按钮的情况下获取输入并执行搜索功能

Javascript get input and perform search function without sumbit button

我正在尝试从文本框中获取输入并使用该值执行搜索而无需提交 button.So 当文本框中的输入更改时,页面将显示相应的搜索研究结果。经过一些在线搜索后,下面是我目前所拥有的。它不起作用。当我在文本框中输入时没有任何反应。有人可以帮忙吗?非常感谢!我也在代码中发表了评论。

<form name="form" method="post"/>   
         <input type="text" id="search" />  //when content in this text box changes, perform goSearch() and display result          
         <script type="text/javascript">                    
            var input = document.getElementById("search");
            function goSearch(){
                    var keyword = input.value; //get the input from textbox
                    //send keyword to search
                    var searchuri= somebaseuri +keyword; //send keyword with uri
                        var xhr = new XMLHttpRequest();
                        xhr.open("GET", searchuri,true);
                        xhr.setRequestHeader("Accept", "application/json");
                        xhr.onload= function(){
                            var list = JSON.parse(xhr.responseText);
                            showResult(list);
                        }   
                        xhr.send(null);                         
                } 
                function showResult(list){
                     //format and display the result we get from the server
                    }

            input.onchange = goSearch(); //when input is changed, perform search function
            input.onblur =goSearch();
        }   
    </script>
</form>

您需要将事件侦听器附加到输入。

document.getElementById("search").addEventListener("yourEvent", function() {
    // Your code to execute.
});

或者,

document.getElementById("search").addEventListener("yourEvent", myFunctionHere);

编辑 1

为了安全起见,完成上述操作后请务必检查控制台是否有任何错误,因为请求也可能会失败。

编辑 2

yourEvent 应该包含您希望它查找的事件,例如在您的情况下是 blur 事件。使用此方法分配事件时,您不需要 on 前缀。

阅读Material

http://www.w3schools.com/jsref/met_document_addeventlistener.asp