Stop reloading page with 'Enter Key'

2019-01-22 17:49发布

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' />

9条回答
爷的心禁止访问
2楼-- · 2019-01-22 18:15

Add onSubmit="return false;" on your form tag

<form onSubmit="return false;">
/* form elements here */
</form>`
查看更多
贪生不怕死
3楼-- · 2019-01-22 18:25

Just use the "action" attribute in <form> tag. Like this

<form action="#">   // your content     </form>
查看更多
趁早两清
4楼-- · 2019-01-22 18:25

Does your JS execute immediately or on document ready? If it's not in a document ready the button won't exist at the time you're trying to call bind.

查看更多
登录 后发表回答