Search code examples
jqueryrequired-field

Making a field required when there are multiple forms


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.


Solution

  • 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