开发者

Iterate over the options in a HTML select with jQuery

开发者 https://www.devze.com 2023-01-19 12:09 出处:网络
I got this example from a blog, but every tim开发者_如何学JAVAe I do this: $(\':input[name=\' + inputName + \']\').each(function(i, selected)

I got this example from a blog, but every tim开发者_如何学JAVAe 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.


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

精彩评论

暂无评论...
验证码 换一张
取 消