JQuery IF option selected

I am trying to check with jQuery if the select parameter with value = 1 is selected and then add the class to some elements. But something is not working. Maybe someone would like a look at the code?

My code is:

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 on violin - http://jsfiddle.net/C7Gg3/

+7
source share
4 answers

You need this inside the event handler:

 $('#rReservation').change(function(){ $('.mRequired').toggleClass('required', $(this).val() == '1'); }); 

http://jsfiddle.net/AlienWebguy/C7Gg3/1/

If you want it to start just at boot, you need to add selected="selected" to one of the options, because until one of them is selected, $('#rReservation").val() will be null . Example : http://jsfiddle.net/AlienWebguy/C7Gg3/3/

+10
source

You should listen to the change event:

 $("#rReservation").change(function(){ if ($("#rReservation").val() == "1") { $('.mRequired').addClass('required'); } else { $('.mRequired').removeClass('required'); } }); 

http://jsfiddle.net/epkN8/

+5
source

Perhaps you want to add / remove a class every time the <select> value changes:

 $(function () { $("#rReservation").change() { $('.mRequired').toggleClass('required', $(this).val() == "1"); } }); 
+3
source

You must make sure that you wrap your code in the change event so that you listen to what is happening.

http://jsfiddle.net/C7Gg3/2/

 $('#rReservation').change(function(){ /* my code goes here */}); 
0
source

All Articles