Mohan Mohan - 3 months ago 10
jQuery Question

submitHandler is not working with external js

I have to handle changes unsaved scenario's in my jsp. I have one jsp form & two external js files.

1) When i click save button inside form, working fine.

2) If i have alert.js code as part of JSP as inline script, Working fine.

3) If i externalize alert.js and included this js as part of import, it is coming inside submit_form() function in app.js. But submitHandler is not been excuted.

1) Jsp form

I have form with inline js click event like below

//submit form with validation
$('button:submit').click(function() {
submit_form('#name', '#siteId', '${add}', '${view}', 'Site');
});


<form:form id="form" action="${save}" commandName="site" cssClass="form-horizontal" data-toggle="validator">
.
.
.
.
<button type="submit" class="btn btn-primary" disabled><spring:message code="form.button.site.save"/></button>
</form:form>


app.js

function submit_form(name, page_id, $add_url, $view_url, page_name) {
$form.validate({
.
.
submitHandler: function(form) {
.
.
$.post($form.attr('action'), $form.serialize(), function(response) {
});
}
});


alert.js

$(document).ready(function() {
//unsaved alert section
var unsaved = false;

$(document).on('change', ':input', ':select', function() { //triggers change in all input/select fields including text type
unsaved = true;
});

$('a.form-done').click(function() {
var $this = $(this);
if(unsaved === true) {
var $modal = $('#unsaveModal');
$modal.find(".modal-title").text("Unsaved Changes");
$modal.find(".modal-body span").html("Changes have not been saved. Do you want to save changes?");
$modal.find('.modal-footer .btn-warning').attr('href', $this.attr('href'));
$modal.modal('show');
return false;
} else {
return;
}
});

$('button:submit').click(function() {
unsaved = false;
});

$('#unsaveModal .modal-footer .btn-primary').click(function() {
$('button:submit').prop('disabled', true);
$('#form').submit();
$('#unsaveModal').modal('hide');
});
});

Answer
function submit_form(name, page_id, $add_url, $view_url, page_name) {
    $form.validate({
        ....
        submitHandler: function(form) {
            ....
        }
    });
    ....

The .validate() method is only used to initialize the plugin on your form and should not be placed inside a click handler, and never inside a submit handler. The plugin is already capturing the click and interrupting the submit event. Putting it inside a submit handler will break it since the submit has already occurred before the plugin initialization was called.

$(document).ready(function() {

    $form.validate({
        ....
        submitHandler: function(form) {
            // ajax here
            ....
        }
    });
    ....