0

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.

James A Mohler
  • 11,060
  • 15
  • 46
  • 72

3 Answers3

4

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

Jonathan Marzullo
  • 6,879
  • 2
  • 40
  • 46
0

change this:

empty_fields = $('form#'+formId+' input, textarea').filter(function(){...});
Snowburnt
  • 6,523
  • 7
  • 30
  • 43
0

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

});
sino
  • 754
  • 1
  • 7
  • 22