0

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>
Sourav
  • 17,065
  • 35
  • 101
  • 159
  • What exactly are you trying to achieve here? There might be better ways to do it. Do you want to execute the function `search()` when the form `searchForm` is submitted? – Shef Jul 21 '11 at 13:27
  • i want to execute search when someone press `enter` key on #text – Sourav Jul 21 '11 at 13:34
  • I gave you an answer, with the appropriate way to solve this issue. – Shef Jul 21 '11 at 13:35

5 Answers5

1

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

$('form').submit(function(ev){
    ev.preventDefault();
    /* your code here */
});
Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
1
<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

genesis
  • 50,477
  • 20
  • 96
  • 125
1

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();
    });
});
Shef
  • 44,808
  • 15
  • 79
  • 90
0

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

Schroedingers Cat
  • 3,099
  • 1
  • 15
  • 33
0

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.

MatTheCat
  • 18,071
  • 6
  • 54
  • 69