Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop reloading page with 'Enter Key'

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' /> 
like image 945
John R Avatar asked Jan 14 '12 22:01

John R


People also ask

Can I stop page refreshing?

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.

How do you disable the Enter key of an input textbox?

Disabling enter key for the formaddEventListener('keypress', function (e) { if (e. keyCode === 13 || e. which === 13) { e. preventDefault(); return false; } });

How do I submit a form using Enter?

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.


2 Answers

Don't bind to the inputs; 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); 
like image 100
icktoofay Avatar answered Sep 23 '22 03:09

icktoofay


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           } }); 
like image 24
opp Avatar answered Sep 25 '22 03:09

opp