changing select's parent li elements class
I have selects in list items. onchange of select, if selected options value is empty, I would like to give the parent li element a "isnotselected" class, else if selected option's value is not empty, I would like to give the parent li element a "i开发者_StackOverflow社区sselected" class. How can I do this via jQuery?
<ul>
<li>
<select>
<option value="">Select Value</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
</li>
<li>
<select>
<option value="">Select Value</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
</li>
<li>
<select>
<option value="">Select Value</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
</li>
<li>
<select>
<option value="">Select Value</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
</li>
</ul>
A Don't Repeat Yourself solution:
var classes = {
'true': 'isselected',
'false': 'isnotselected'
};
$('select').change(function () {
var sel = !!$(this).val(); // convert value into true/false
$(this).closest('li').addClass(classes[sel]).removeClass(classes[!sel]);
});
Demo: http://jsfiddle.net/B5Q7m/
Alternatively but in the same style, you can rely on the fact that false
converts to 0 and 'true' converts to 1, although the classes
declaration isn't as descriptive:
var classes = ['isnotselected', 'isselected'];
$('select').change(function () {
var sel = !!$(this).val();
$(this).closest('li').addClass(classes[+sel]).removeClass(classes[+(!sel)]);
});
Note: .parent()
can be used in place of .closest('li')
, but .closest
is usually the safer option in case you decide to wrap the <select>
s in another element later on.
Very simple:
var classes = ['isnotselected', 'isselected'];
$('ul li select').change(function() {
$(this).closest('li')
.removeClass(classes.join(' '))
.addClass(classes[Number(this.value.length > 0)]);
});
I assume you also want to remove the opposite class if it is present. You need to check the .val()
of the event target on the change event like so:
$('select').bind('change',function(e){
$et = $(e.target);
if ($et.val() === "") {
$et.parent().removeClass('isselected')
.addClass('isnotselected');
} else {
$et.parent().removeClass('isnotselected')
.addClass('isselected');
}
});
I have created a demo here (link).
Example on jsfiddle
$("select").change(function(){
var $li = $(this).parents("li");
$li.removeClass("isselected").removeClass("isnotselected");
if($(this).val())
{
$li.addClass("isselected");
}
else
{
$li.addClass("isnotselected");
}
});
All you need to do is register the change event to the select element to add remove the class isselected and isnotselected.
精彩评论