TIMEX
TIMEX

Reputation: 271584

How do I do this SELECT/OPTION in HTML? (javascript)

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)

Upvotes: 1

Views: 1100

Answers (4)

animuson
animuson

Reputation: 54719

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.

Upvotes: 1

Nick Presta
Nick Presta

Reputation: 28665

$("#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.

Upvotes: 2

Chetan S
Chetan S

Reputation: 23803

$("#myselect").change(function() {
    alert($(this).find("option:selected").attr("rel"));
});

Upvotes: 3

middus
middus

Reputation: 9121

How about this?

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

Should work for multiple selects, too.

Upvotes: 2

Related Questions