admin管理员组

文章数量:1321260

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.

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.

Share Improve this question asked Oct 12, 2010 at 12:02 vtortolavtortola 36k31 gold badges167 silver badges267 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

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

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());
});

Without seeing your html, try this:

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

本文标签: javascriptIterate over the options in a HTML select with jQueryStack Overflow