jquery click() in submit button

2019-06-15 21:25发布

问题:

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.

回答1:

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
});


回答2:

It would be best to attach the value update directly to the form's submit handler like this

$("#submitId").closest("form").submit(function () {
 $('#hiddenInput').val(someVariable);
});


回答3:

I personally think it is safer to prevent submit, then set value of input needed and only then submit the form programmatically. Like:

$("form").submit(function (e) {
    e.preventDefault();
    $('#hiddenInput').val(someVariable);
    $(this).submit();
});


回答4:

The .click() should always be run first.