jQuery – Checking value of various input types

I have no idea what I’m doing wrong here. I have a form with radio buttons and simple text fields. I’m checking to see if there is a value within the form fields or if either of the radio buttons have been checked. If there is no value add a red color to the label. If they have a value I’m adding back the default black. But for some reason no matter if I put a value in the text field it stays red. Also kind of strange but if I check the first checkbox the black text appears. Any help is greatly appreciated.

JS Fiddle: http://jsfiddle.net/5Sacj/

<form name="headerForm">
  <label id="gender" for="gender">Gender</label>
  <input type="radio" name="customer" value="male" />Male
  <input type="radio" name="customer" value="female" />Female
<br/>
  <label for="fname">*First Name</label>
  <input type="text" class="text" id="fname" name="fname" />
<br/>    
  <label for="fname">*Last Name</label>
  <input type="text" class="text" id="lname" name="lname" />
  <input id="submit" type="submit" name="submit" value="submit"
</form>   

JQUERY

$(document).ready(function() {    
$("#submit").on('click', function() {
    $(":text, :radio").each(function() {
        if($(this).val() === '' || !$(this).is(':checked')){
            $(this).prev('label').css('color','red');
        } else { 
            $(this).prev('label').css('color','black');
        }
    });
});
});

Answer

That is because you are using or operator ||.

It will execute even if one is true. Try using && or have separate if condition for both.

Leave a Reply

Your email address will not be published. Required fields are marked *