Delmon Young
Delmon Young

Reputation: 2053

Set flag when looping through input fields

I have a series of multiple text fields and a text area. I’m looping through the text fields and the text area and checking if there is a value. If there is not a value I set a flag that says pass=false. Otherwise I set pass=true and would like to fire a custom event if everything evaluates to true. The problem is that because one input field evaluates to true it evaluates them all to true even though two of the fields have no value in them. How would I go about doing this if I wanted it so that all fields have to be filled in but still set pass=false if one or two of them are filled in? Any help is greatly appreciated!

JS Fiddle link: http://jsfiddle.net/YyAjp/12/

HTML:

<form name="headerForm">
  <label for="fname">*First Name</label>
  <input type="text" class="text" id="fname" name="fname" />
  <br/>   

  <label for="mname">*Middle Name</label>
  <input type="text" class="text" id="mname" name="mname" />
  <br/>     

  <label for="fname">*Last Name</label>
  <input type="text" class="text" id="lname" name="lname" />
  <br/>    

  <label for="notes">*Notes</label>
  <textarea name="notes" /></textarea>

  <a href="#" id="submit">Submit</a>
</form>   

JQUERY

$(document).ready(function() {       
$("#submit").on('click', function() {    
    var pass;
    $("input,textarea,select").each(function() {
        if($(this).val() === ''){
            pass = false;
            $(this).prev('label').css('color','red');
        } else { 
            pass = true;
            $(this).prev('label').css('color','black');
        }
    });
    console.log(pass);
    if(pass){ alert('trigger custom event') } else { alert('pass failed'); }
});                    
});

Upvotes: 0

Views: 1402

Answers (1)

Blazemonger
Blazemonger

Reputation: 92963

Change

pass = true;

into

pass = pass && true;

and initialize it to true:

$("#submit").on('click', function() {    
    var pass = true;

http://jsfiddle.net/mblase75/pgM5X/

(You might also want to use $.trim() on the values first.)

Upvotes: 1

Related Questions