Change color of input labels with jquery validate

I'm trying to change the class of my form input labels when a specific field fails to validate. I want to add the 'error' class to the spans directly above any invalid form elements.

This is what my HTML looks like:

<span class="label">What kind service do you need?</span><br />
<div style="float: left; width: 220px; margin: 5px 21px 0 0;"><input type="checkbox" name="serviceType"><label>Option 1</label></div>
<div style="float: left; width: 220px; margin: 5px 21px 0 0;"><input type="checkbox" name="serviceType"><label>Option 2</label></div>
<div style="float: left; width: 220px; margin: 5px 21px 0 0;"><input type="checkbox" name="serviceType"><label>Option 3</label></div>
<div style="float: left; width: 220px; margin: 5px 0 0 0;"><input type="checkbox" name="serviceType"><label>Option 4</label></div>
<div id="clear"></div>

<span class="label">When do you need service?</span><br />
<div id="inputSmall"><input type="text" class="small" name="serviceDate" /></div>

<span class="label">How often?</span><br />
<div id="inputSmall"><select class="small" name="recurringBasis">
<option value=""></option>
<option value="single">One time</option>
<option value="weekly">One a week</option>
</select></div>

And this is my JS:

$("#quote").validate({
  rules: {
    serviceDate: "required",
    recurringBasis: "required",
    serviceType: {
        required: true,
        minlength: 1            
    }
  },
  highlight: function(element) {
    $(element).prev('span').addClass("error");
  },
  unhighlight: function(element) {
    $(element).prev('span').removeClass("error");
  }
});

I've seen suggestions to use the highlight/unhighlight approach, but that doesn't appear to work. Any help would be greatly appreciated.

Answers


your selector $(element).prev('span') is wrong

Try

$(element).parent().prev().prev('span')

Demo: Fiddle


Need Your Help

set a JTextField width in maner to wrap a given text

java string swing jtextfield

I have an uneditable and disabled JtextField in which I will put a String obtained after requesting a Database, and I want that this JtextField wraps All my String.