Если вы хотите отправить форму, используя ссылку:
HTML -
<form action="my-page.php" id="my-form" method="post">...</form>
<a href="#" id="form-submit">SUBMIT</a>
JS -
$(function () {
$('#form-submit').on('click', function () {
//fire the submit event on the form
$('#my-form').trigger('submit');
//stop the default behavior of the link
return false;
});
});
Документы для trigger()
: http://api.jquery.com/trigger
Если вы хотите отправить форму, не покидая страницы, вы можете использовать вызов AJAX:
$(function () {
$('#form-submit').on('click', function () {
//cache the form element for use later
var $form = $('#my-form');
$.ajax({
url : $form.attr('action') || '',//set the action of the AJAX request
type : $form.attr('method') || 'get',//set the method of the AJAX reqeuest
data : $form.serialize(),
success : function (serverResponse) {
//you can do what you want now, the form has been submitted, and you have received the serverResponse
alert('Form Submitted!');
}
});
});
$('#my-form').on('submit', function () {
//stop the normal submission of the form, for instance if someone presses the enter key inside a text input
return false;
});
});
Документы для $.ajax()
: http://api.jquery.com/jquery.ajax
Обратите внимание, что .on()
является новым в jQuery 1.7 и в этом случае аналогично использованию .bind()
.