jquery - targetting a select using $this

Posted by Maureen on Stack Overflow See other posts from Stack Overflow or by Maureen
Published on 2012-11-04T04:47:34Z Indexed on 2012/11/04 5:00 UTC
Read the original article Hit count: 212

Filed under:
|

I am trying to get individual selects (which have the same class as other selects) to respond to a .change function, however it only works on one of the selects. If you test out this code it will make more sense. Try to add a few "ON/OFF events", and then select "Specified Time" in the various selects. You'll see only the first one responds. Any ideas?

Thanks!

Please see the following code:

$(document).ready(function() {
   var neweventstring = '<div class="event">Turns <select name="ONOFF"><option value="On">ON</option><option value="Off">OFF</option></select> at: <select name="setto" class="setto"><option>Select Time</option><option value="Sunrise">Sunrise</option><option value="Sunset">Sunset</option><option value="specifiedtime">Specified Time</option></select></div>';

   $('#addmondaysevent').click(function () {
      $('#monday .events').append(neweventstring);
   });

   $('.setto').change(function() {  
      alert('The function is called');
      if($("option:selected", this).val() =="specifiedtime"){
          alert('If returns true');
          $(this).css("background-color", "#cc0000");
          $(this).after('<div class="specifictime"><input type="text" value="00" style="width:30px"/> : <input type="text" value="00"  style="width:30px"> <select name="ampm"><option value="AM" selected>AM</option><option value="PM">PM</option></select></div>')
          }
   });
});

And my HTML:

<div id="monday">
    <h2>Mondays</h2>

     <div class="events">
     <div class="event">
            Turn 
            <select name="ONOFF">
            <option value="On">ON</option>
            <option value="Off">OFF</option>
            </select>
            at: 
            <select name="setto" class="setto">
            <option>Select Time</option>
            <option value="Sunrise">Sunrise</option>
            <option value="Sunset">Sunset</option>
            <option value="specifiedtime">Specified Time</option>
            </select>
       </div>
      [<a id="addmondaysevent">Add an ON/OFF event</a>] 
    </div>
</div>

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about target