Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery click() in submit button

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.

like image 296
iteam Avatar asked Nov 04 '14 23:11

iteam


People also ask

How do you submit a form when a button is clicked?

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.

How can create Submit button in jQuery?

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" ).


1 Answers

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
});
like image 165
PeterKA Avatar answered Oct 16 '22 15:10

PeterKA