I am trying to check with jQuery if the select option with value = 1 is selected then add class to some elements. But something don't work. Can please some one look at the code?
My code :
Reservation <br/>
<select id="rReservation" name="rReservation" class="">
<option value="0">Maybe</option>
<option value="1">Sure</option>
</select>
<hr/>
Name <br/>
<input type="text" name="rCardUser" class="mRequired" />
<hr/>
Card<br/>
<input type="text" name="rCardNrr" class="mRequired" />
jQuery
if ($("#rReservation").val() == "1") {
$('.mRequired').addClass('required');
} else {
$('.mRequired').removeClass('required');
}
LIVE example at fiddle - http://jsfiddle.net/C7Gg3/
You need it inside an event handler:
$('#rReservation').change(function(){
$('.mRequired').toggleClass('required', $(this).val() == '1');
});
http://jsfiddle.net/AlienWebguy/C7Gg3/1/
If you want it to trigger simply on load, you need to add selected="selected"
to one of the options, because until one is "selected", $('#rReservation").val()
will be null
. Example: http://jsfiddle.net/AlienWebguy/C7Gg3/3/
You have to listen to the change
event:
$("#rReservation").change(function(){
if ($("#rReservation").val() == "1") {
$('.mRequired').addClass('required');
} else {
$('.mRequired').removeClass('required');
}
});
http://jsfiddle.net/epkN8/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With