vtortola
vtortola

Reputation: 35963

Iterate over the options in a HTML select with jQuery

I got this example from a blog, but every time I do this:

$(':input[name=' + inputName + ']').each(function(i, selected)
{
    alert($(selected).text());
});

I got all an alert with all the options together :(

I have to search by the input name always, the inputs have no id.

Which is the right way to do it?

Kind regards.

Upvotes: 2

Views: 6068

Answers (3)

Stephen
Stephen

Reputation: 18984

Without seeing your html, try this:

$(":input[name='" + inputName + "'] option").each(function(i, selected) {
    alert($(selected).text());
});

Upvotes: 1

Bobby Borszich
Bobby Borszich

Reputation: 11767

Assuming your HTML is similar to this

<SELECT NAME="mylist">
  <option>Volvo</option>
  <option>Saab</option>
  <option>Mercedes</option>
  <option>Audi</option>
</SELECT>

you need to modify your selector to iterate over the <OPTION> tags, your selector was iterating over the <SELECT> tag

var inputName = mylist;
$(':input[name=' + inputName + '] option').each(function(i, selected)    {
        alert($(selected).text());
});

Upvotes: 1

Nikita Rybak
Nikita Rybak

Reputation: 68046

That's because select tag is found by jquery, not option tags

This will give you list of the options.

$(':input[name=' + inputName + '] option').each(function(i, selected) {
    alert($(selected).text());
});

An example

Upvotes: 5

Related Questions