I have a .click() function on a submit button in a form:
$("#submitId").click(function () {
$('#hiddenInput').val(someVariable);
});
It works like a charm. When the submit button is clicked the click() function fills the hidden input variable and then the whole form gets submitted. The server then receives the hidden input with the refreshed content.
My question is: will it always work? Is there any danger that, by some reason not yet known to me, the submit operation gets executed first and the click() function later? I want to make sure the hidden input always gets refreshed.
In javascript onclick event , you can use form. submit() method to submit form. You can perform submit action by, submit button, by clicking on hyperlink, button and image tag etc. You can also perform javascript form submission by form attributes like id, name, class, tag name as well.
Answer: Use the jQuery submit() Method You can use the submit() method to submit an HTML form (i.e. <form> ) using jQuery. The jQuery code in the following example will submit the form on click of the button (i.e. the <button> element) which has the type attribute set to button (i.e. type="button" ).
When working with forms, it's always advisable to let the submit
button do it's job: TRIGGER THE FORM'S SUBMIT EVENT ... that's what it's meant for. Then you would listen for the submit
event on the form
rather than the click
event on the submit
button.
You can use event.preventDefault()
to prevent default submission of the form so that you can do some house keeping then you can submit the form.
$("#submitId").closest('form').on('submit', function(event) {
event.preventDefault();
$('#hiddenInput').val(someVariable); //perform some operations
this.submit(); //now submit the form
});
Or simply,
$('form').on('submit', function(event) {
event.preventDefault();
$('#hiddenInput').val(someVariable); //perform some operations
this.submit(); //now submit the form
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With