Ultimately I am trying to run some code which depends on the value (or data stored in any attribute, like rel, etc.) of a select‘s option, when that option gets selected. I have the following code:
JavaScript:
$('select#select1').change(function () {
set = $('#select1 option:selected').val();
alert(set);
// $('#select2').html()
});
HTML:
<select id="select1">
<option value="1" rel="1">First</option>
<option value="2" rel="2">Second</option>
<option value="3" rel="3">Third</option>
<option value="4" rel="4" selected="selected">Fourth</option>
</select>
There are actually two problems here. Firstly, the code above does nothing, as the change function doesn’t seem to recognize the $('select#select1') selector on the first line. If I change it to just $('select'), it works. But this is no good, as there are several select elements on my page and I need to distinguish which one.
Secondly, if I get it working temporarily with $('select') (and deleting other select elements on the page) then I always get the value “1” being alerted, no matter which of the 4 options I select.
Same happens if I use $('#select1 option:selected').attr('rel'); instead.
For the love of God, why?
Try wrapping it inside
$(document).ready(function () {... });and use$(this).val()inside your handler. See below,DEMO