遍历多个选择组合框JQuery中的选定值 [英] Looping through selected values in multiple select combobox JQuery

查看:70
本文介绍了遍历多个选择组合框JQuery中的选定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况.

我有一个组合框,可以进行多种选择.

I have a combobox where multiple selection is available.

                <select id="a" multiple="multiple">
                    <option value="">aaaa</option>
                    <option value="">bbbb</option>
                    <option value="">cccc</option>
                    <option value="">dddd</option>
                </select>

现在我也有一个按钮

<button type="button" id="display">Display</button>

用户单击此按钮时,应在警报框中列出下拉菜单的所有选定值

When a user clicks on this button, it should list all the selected values of the dropdown in an alert box

我的JS代码如下

  $(document).ready(function() {
                $('#display').click(function(){
                    alert($('#a').val());
                });


        });

任何指针都会受到赞赏

推荐答案

您必须找到所有选定的选项:

You have to find all the selected options:

jQuery(function($) {
    $('#display').click(function() {
        $('#a > :selected').each(function() {
            alert($(this).text());   // using text() here, because the 
        });                          // options have no value..?
    });
});


Pim指出,该手册非常有用:


The manual, as Pim pointed out, is useful:

.val()方法主要用于获取表单元素的值.对于<select multiple="multiple">元素,.val()方法将返回一个包含每个选定选项的数组.

The .val() method is primarily used to get the values of form elements. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option.

因此,上面的方法应该可以工作,但是jQuery已经在后台为您完成了这项工作,因此这要容易得多:

So, the above should work, but jQuery already does this behind the scenes for you, so this is much easier:

alert($('#a').val().join(", "));

如果它对您不起作用,则可能是因为您的选择似乎没有价值.

If it's not working for you, it might be because of the fact that your options don't seem to have a value.

这篇关于遍历多个选择组合框JQuery中的选定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆