Add class when (...) with jQuery
I've this simple code:
HTML:
<input type="text" name="name" class="required" />
<select id="options" name="options" size="1">
<option value="0"> YES </option>
<option value="1"> NO </option>
</select>
<input type="text" name="email" />
<input type="text" name="city" />
Question:
I want to add class = "required"
to email
and city
fields when options
is e开发者_运维问答qual to 1
Something like:
$('#options').change(function() {
$('input[name="email"], input[name="city"]')
.toggleClass('required', this.value === '1');
});
Reference: change
, toggleClass
I've added Id's to your input elements to make the selector quicker:
<input type="text" name="email" id="email" />
<input type="text" name="city" id="city" />
jQuery:
$("#options").change(function() {
if ($(this).val() == "1") {
$("#email, #city").addClass("required");
}
else {
$("#email, #city").removeClass("required");
}
});
if( $('#options').val() == "1"){
$('#email, #city').addClass('required');
}
assign ids to the inputs and do following logic , ids are always better as it takes less time to execute in case of complex DOMs.
$('#options').change(function(){
if($(this).val() == 1) {
$('#inputemail').addClass('required');
$('#city').addClass('required');
}else {
$('#inputemail').removeClass('required');
$('#city').removeClass('required');
}
});
精彩评论