M B M B - 4 months ago 14
jQuery Question

Jquery select only from modal page

I have a webpage that opens a modal form. I validate the modal form using a JQuery function. The problem is that my function is checking all fields in both the modal AND the page behind it.

//validate function
function validateFields() {
var valid = true;
$('.required').each(function () {
if (!$(this).val()) {
addError(this, 'required');
valid = false;
}
});
}

//in my save function
function saveLead(){
if (validateFields()) {
//save
}
}


My validate function is checking all fields with the
required
class on both my page and modal. How can I get it to just use my page?

UPDATE:
this has complications because my validation function is reused on many pages and is not set up to accept a specific form to check

Is such a thing possible or do I have to do major revisions to the validation or modal in order for this to work?

Answer

You could detect the form from which the submit button is clicked. Something like the below should work.

//validate function 
function validateFields($submittedForm) {
    var valid = true;
    $('$submittedForm .required').each(function () {
        if (!$(this).val()) {
            addError(this, 'required');
            valid = false;
        }
    });
}

//in my save function

// Find the form there 'this' is the submit button
var $submittedForm = $(this).closest('form');

function saveLead($submittedForm){
    if (validateFields($submittedForm)) {
         //save
    }
}