Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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' />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
250 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...