views:

59

answers:

4

Suppose I have this:

<select id="myselect">
<option rel="a">1</option>
<option rel="b">2</option>
<select>

How do I use JQuery so that onchange $("#myselect"), I alert the "rel" part of the option (not 1 or 2)

+2  A: 

How about this?

$("myselect").change(function(){
  $(this).children("option:selected").each(function () {
            alert($(this).attr('rel');
          });
});

Should work for multiple selects, too.

middus
+1 for code twin!
Nick Presta
+3  A: 
$("#myselect").change(function() {
    alert($(this).find("option:selected").attr("rel"));
});
Chetan Sastry
+2  A: 
$("#myselect").change(function() {
    $("#myselect option:selected").each(function () {
        alert($(this).attr('rel'));
    });
});

Just to mention, my code will also work if you have the multiple="multiple" attribute on your SELECT element, alerting both values.

Nick Presta
+1 Your code is my code (almost). OR vice versa!? :P
middus
+1  A: 

The 'rel' attribute is not supported on an option element, you should be using the 'value' attribute to specify a value for your options. I'm sure jQuery can fetch that much easier than an unsupported attribute.

animuson