0

There's a lot of other stuff going on, but I have this working code which uses a click function on two divs which does a bunch of other stuff, like this:

<div id="Single">Single</div><div id="Regular">Regular</div>

Here's the function:

$(document).on('click', '#Single , #Regular', singleToDDSwitch);

I need to keep the same functionality but use a select list as the trigger instead. Here's the example select list:

<select><option id='Single'>Single</option><option id='Regular'>Regular</option></select>

Can anyone help, I'm not that hot at jQuery?

richardpixel
  • 291
  • 1
  • 4
  • 9

2 Answers2

1

Try this:

$(document).ready(function() {
  $(document).on('change', '#sel', function() {
    alert($(this).find(":selected").text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
  <option>Single</option>
  <option>Regular</option>
</select>

In select you dont neet the individual ids.

P. Jairaj
  • 1,033
  • 1
  • 6
  • 8
0

You can use the .change event on the <select> element.

unbindall
  • 514
  • 1
  • 13
  • 29
  • 2
    Yes, but this doesn't really answer the question... maybe an example would be more helpful? – wahwahwah Jan 29 '16 at 19:06
  • `.change()` doesn't bind to dynamic elements .... Surely you mean `.on('change')` – Zak Jan 29 '16 at 19:06
  • $( "select" ).change(function() { alert( "A change has occured" ); }); – TreeHouseFalcon Jan 29 '16 at 19:07
  • Go ahead and try that with a dynamically created element .. Your method will not work. Do some research on a .click()/.change .... etc vs .on('click')/.on('change') .. There is also a place for .live() (depricated in 1.7) over a strict .change() binding ... http://stackoverflow.com/questions/6658752/click-event-doesnt-work-on-dynamically-generated-elements – Zak Jan 29 '16 at 19:11
  • Thanks, will investigate further. – richardpixel Jan 29 '16 at 19:22
  • @Zak - technically the question didn't mention that it was dynamically created element so his approach is valid for the scenario. Neither is specifically better than the other depending on your requirements; delegated event handlers cost you at the time of triggering, direct event handlers cost you at the time of binding... – Reddog Feb 19 '16 at 01:17