简体   繁体   中英

Loop through each 'required' field in form submission

I'm having real trouble here. I can't wrap my brain around this!

What I want to do is submit a form after validating the email address and then each input that I have labeled with a class of 'required'. I would really appreciate someone showing me how to loop through those and only submit if each one is filled in.

<script type="text/javascript">
    $(document).ready(function() {
        $('.button').click(function() {
            var email = $("input.email").val();        
            var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
            if(filter.test(email)) {
                $('input.required').each(function() {
                    var name = $("input.required").val();
                    if(name != "") {
                        $('#form').submit();
                    } else {
                        $('#error').show();
                        return false;
                    }
                });
            } 
            else {
                $('#error').show();
                return false;
            }
        });
    });
</script>

You can use the .filter() to filter out only elements that are empty, and then check the number of element that matched the filter. If any input matched the filter, you have an error and shouldn't post it. Something like this:

var emptyFields = $('input.required').filter(function() {
    return $(this).val() === "";
}).length;

if (emptyFields === 0) {
   $('#form').submit();
} else {
   $('#error').show();
   return false;
}
    var isValid = true;  // Set the isValid to flag try initially

    $('input.required').each(function() {   // Loop thru all the elements
        var name = $("input.required").val();
        if(name != "") {  // If not empty do nothing

        } else {          
            isValid = false; // If one loop is empty set the isValid flag to false
            return false;    // Break out of .each loop 
        }
    });

    if(isValid){    // If valid submit form else show error
      $('#form').submit();
    }
    else{
       $('#error').show();
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM