I have a search box at the top of page that makes an ajax call when a user hits the adjacent button. I am trying to update the input tag so that when a user hit the 'enter' key, the apropriate JavaScript takes place without reloading the page. The problem is that the page keeps reloading. Here is my latest attempt:
$("searchText").bind('keyup', function(event){ if(event.keyCode == 13){ event.preventDefault(); $("#buttonSrch").click(); return false; } }); <input type='search' id='searchText' /> <input type='button' id='buttonSrch' onclick="search(document.getElementById('searchText'))" value='Search' />
Click the Start button, type “internet options” and select Internet Options in the search results. In the Internet Properties window, click “Custom tab -> Custom level,” then in the Security Settings window, scroll down until you find “Allow META REFRESH.” Disable this option and click OK.
Disabling enter key for the formaddEventListener('keypress', function (e) { if (e. keyCode === 13 || e. which === 13) { e. preventDefault(); return false; } });
To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. Explanation: We use the jQuery event. which to check the keycode on the keypress.
Don't bind to the input
s; bind to the form
. Assuming the form
has an ID of searchForm
:
$("#searchForm").submit(function() { search($("#searchText").get(0)); return false; });
Try it out.
It can also be done with plain JavaScript:
document.getElementById('searchForm').addEventListener('submit', function(e) { search(document.getElementById('searchText')); e.preventDefault(); }, false);
I know its a little late but I ran into the same problem as you. It worked for me using "keypress" instead of bind.
$('#searchText').keypress(function (e) { if (e.which == 13) { e.preventDefault(); //do something } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With