I'm pretty new to jquery so bear with me. I'm currently looping through a set of form elements and trying to select a specific one and do something with it. I'm running into some troubles and just can't figure this out. My below code loops through all the form elements and I'm trying to target an input field with an id of zip code and do some special zip code validation with it. Except it hits the zip code validation first (even though it's the 3rd input element) and validates it then goes through all the other form elements and validates the zip code a second time. How would I prevent a) the zip code validation being hit twice and b) zip code not being the first input element validated but instead being the 3rd.
$("#homeForm :input").each(function(){
if($("#zipCode").val().length == 0){
//do some zip code validation
}
if($(this).val().length == 0 && $(this).is(":visible")){
//do some regular validation
}
});
My html is here:
<form id="homeForm>
<input type="text" name="fullName" id="fullName" />
<input type="text" name="homePhone" id="homePhone" />
<input type="text" name="zipCode" id="zipCode" />
<input type="text" name="age" id="age" />
<input type="text" name="homeTown" id="homeTown" />
</form>
Newbie here and any help is greatly appreciated.
if( this.id == 'zipCode' && !this.value.length)as the zipcode element is probably part of the form and is already being iterated, otherwise you validate the zipcode element on each and every iteration.