Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery IF option selected

Tags:

jquery

select

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/

like image 847
iKaspars Avatar asked Aug 18 '11 18:08

iKaspars


2 Answers

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/

like image 138
AlienWebguy Avatar answered Oct 02 '22 00:10

AlienWebguy


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/

like image 22
Joseph Silber Avatar answered Oct 02 '22 00:10

Joseph Silber