Pregunta

I have a page with multiple forms. I can simulate a required field via

$('form').submit(function () {
    var empty_fields = $('input, textarea').filter(function () {

        //return empty required fields
        return $(this).attr("required") && $(this).val() === "";
    });

    // if empty required field stop the form submitting and let the user know
    if (empty_fields.length) {
        alert('All required fields must have data');
        return false;
    }

});

But if there are multiple forms on a page and one has a required field, then the other forms are impacted.

¿Fue útil?

Solución

why not use 'this' to reference the 'form' element you binded your submit handler to:

$('form').submit(function () {

    var $this = $(this);  // $(this) is the 'form' field tag you binded to

    var empty_fields = $this.find('input, textarea').filter(function () {

       //return empty required fields
       return $(this).attr("required") && $(this).val() === "";
    });

    // if empty required field stop the form submitting and let the user know
    if (empty_fields.length) {
          alert('All required fields must have data');
          return false;
    }
});

so this way you are only taking action on the scope of 'this' which is the form element your binding the submit to, and then *find*ing a input and textarea tag within it

Otros consejos

change this:

empty_fields = $('form#'+formId+' input, textarea').filter(function(){...});

do this :

$('form').submit(function () {
    var empty_fields = $('input, textarea').filter(function () {

        //return empty required fields
        return $(this).attr("required") && $(this).val() === "";
    });

    // if empty required field stop the form submitting and let the user know
    if ($(this).hasClass("form1") &&  empty_fields.length) {
        alert('All required fields must have data');
        return false;
    }

});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top