Using jQuery, is it true that we can catch the submit button's event either by "click" or "submit"?
In jQuery, for a form submit button or image, it seems that we can use either
$('#search-box-submit').click(function() {
if ($('#search-box-submit').val().match(/^\s*$/)) {
alert("Please enter search keywords");
return false; // stop the search request
}
});
or we can use submit
:
$('#search-box-submit').submit(function() {
if ($('#search-box-submit').val().match(/^\s*$/)) {
alert("Please enter search keywords");
return false; // stop the search request
}
});
update: actually, click
works to prevent an empty keyword being used for searching, but submit
doesn't prevent that. Why is that?
update 2: I am so surprised that in Firefox开发者_开发百科 or Chrome, defining the click
handler actually works for pressing Enter with nothing entered as well. So looks like Firefox and Chrome build that intelligence in. If I use IE 8, then it will go ahead and search with empty string (request to server)
You're comparing two different events for two elements. The click event is for the button and the submit event is for the form. The reason that returning false inside of the click prevents the form from being submitted is that the form is never notified of the click event. You'll want to be using submit though.
submit
is the one you should use. click
will only fire if you click the button. However, there are other ways to submit the form (e.g. pressing enter from one of the form fields).
See the following for more about returning false
and preventing the default event:
Submit behavior is acting differently when pressing a button compared to pressing enter
From your update, submit
should be bound to the form, not the submit button.
At a glance, it looks like you're setting your submit handler on the wrong element.
When capturing form submits like this, it's typically best to catch the actual submit event, rather than the submit button's click event, as not all browsers simulate a click event when the user presses Enter.
However, the submit event only applies to the form itself, not the submit button. I'm not certain how your HTML is set up, but here's what I'd do, and hopefully you can adapt it to your situation easily enough.
<!-- HTML -->
<form id="search-box" action="/search">
<label>Search: <input name="q"></label>
<button type="submit">Go</button>
</form>
// Javascript
$("#search-box").submit(function(event) {
if ($("input", this).val().match(/^\s*$/)) {
alert("Please enter search keywords");
event.preventDefault();
}
});
精彩评论