Friday 12 November 2010

jQuery .submit() method

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form element has focus.

Depending on the browser, the Enter key may only cause a form submission if the form has exactly one text field, or only when there is a submit button present. The interface should not rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key.

For example, consider the HTML:

<form id="target" action="destination.html">
<input type="text" value="Hello there" />
<input type="submit" value="Go" />
</form>
<div id="other">
Click here to trigger the handler
</div>

The event handler can be bound to the form:

$('#target').submit(function() {
alert('It is from submit() handler');
return false;
});

ow when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler. We can trigger the event manually when another element is clicked:

$('#other').click(function() {
$('#target').submit();
});

jQuery API

No comments:

Post a Comment