Sourav
Sourav

Reputation: 17530

Trigger function on Enter keypress

I've a simple search function which i Want to trigger on Enter key press, though the function executes but the form also get posted.

<script>
function search()
{
 ...
}

$(document).ready(function() {
  $("#text").keypress(function (e) {
if (e.which==13)
  search();
 });
});

<body>
<form id="searchForm" name="searchForm">
 <input size="40" id="text" type="text" name="text" class="input" />
</form>
</body>

Upvotes: 0

Views: 3254

Answers (5)

genesis
genesis

Reputation: 50966

<script>
function search()
{
 ...
}

$(document).ready(function() {
  $("#text").keypress(function (e) {
if (e.which==13)

  search();
  return false;
 });
});
</script>

use return false, it prevents default action

Upvotes: 1

Shef
Shef

Reputation: 45589

There is no need to listen for an Enter key press event. You should listen for the submit event, which will also fire when the key is pressed.

Here is the proper way to do it:

$(document).ready(function() {
    $("#searchForm").submit(function (e) {
        e.preventDefault();
        search();
    });
});

Upvotes: 1

MatTheCat
MatTheCat

Reputation: 18721

It's the way forms work, you should use submit event: http://api.jquery.com/submit/

Use preventDefault or just return false to cancel the natural submit action.

Upvotes: 0

Schroedingers Cat
Schroedingers Cat

Reputation: 3129

You can try returning false from your function which will stop the processing continuing.

Upvotes: 0

Adam Hopkinson
Adam Hopkinson

Reputation: 28795

Bind the function to the submit event and prevent the default:

$('form').submit(function(ev){
    ev.preventDefault();
    /* your code here */
});

Upvotes: 1

Related Questions