I've a simple search function which i Want to trigger on Enter key press, though the func开发者_如何学Ction 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>
Bind the function to the submit event and prevent the default:
$('form').submit(function(ev){
ev.preventDefault();
/* your code here */
});
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();
});
});
<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
You can try returning false from your function which will stop the processing continuing.
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.
精彩评论