Javascript 使用 jQuery 或纯 JS 获取多选框的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2543322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:49:43  来源:igfitidea点击:

Get value of multiselect box using jQuery or pure JS

javascriptjqueryjquery-selectorsjquery-validatedom-events

提问by Hulk

In the code shown below, how to get the values of multiselect box in function val()using jQuery or pure JavaScript?

在下面的代码中,如何val()使用jQuery或纯JavaScript获取函数中多选框的值?

<script>
    function val() {
        //Get values of mutliselect drop down box
    }

    $(document).ready(function () {
        var flag = 0;
        $('#emp').change(function () {
            var sub = $("OPTION:selected", this).val()
            if (flag == 1) $('#new_row').remove();
            $('#topics').val('');
            var html = '<tr id="new_row" class="new_row"><td>Topics:</td><td>  <select    id="topic_l" name="topic_l" class="topic_l" multiple="multiple">';
            var idarr = new Array();
            var valarr = new Array(); { %
                for top in dict.tops %
            }
            idarr.push('{{top.is}}');
            valarr.push('{{pic.ele}}'); { % endfor %
            }
            for (var i = 0; i < idarr.length; i++) {
                if (sub == idarr[i]) {
                    html += '<option value="' + idarr[i] + '" >' + valarr[i] + '</option>';
                }
            }
            html += '</select></p></td></tr>';
            $('#tops').append(html);
            flag = 1;
        });
    });
</script>
Emp:&nbsp;&nbsp;&nbsp;&nbsp;
<select id="emp" name="emp">
    <option value=""></option>
    <option value="1">1</option>
</select>

<div name="tops" id="tops"></div>

<input type="submit" value="Create Template" id="create" onclick="javascript:var ret=val();return ret;">

回答by prodigitalson

the valfunction called from the selectwill return an array if its a multiple. $('select#my_multiselect').val()will return an array of the values for the selected options - you dont need to loop through and get them yourself.

如果它是一个倍数,val则从 调用的函数select将返回一个数组。$('select#my_multiselect').val()将返回所选选项的值数组 - 您不需要自己遍历并获取它们。

回答by Etdashou

I think the answer may be easier to understand like this:

我认为这样的答案可能更容易理解:

$('#empid').on('change',function() {
  alert($(this).val());
  console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="empid" name="empname" multiple="multiple">
  <option value="0">Potato</option>
  <option value="1">Carrot</option>
  <option value="2">Apple</option>
  <option value="3">Raisins</option>
  <option value="4">Peanut</option>
</select>
<br />
Hold CTRL / CMD for selecting multiple fields

If you select "Carrot" and "Raisins" in the list, the output will be "1,3".

如果在列表中选择“Carrot”和“Raisins”,输出将为“1,3”。

回答by aykut aydo?an

var data=[];
var $el=$("#my-select");
$el.find('option:selected').each(function(){
    data.push({value:$(this).val(),text:$(this).text()});
});
console.log(data)

回答by Yulian

According to the widget's page, it should be:

根据小部件的页面,它应该是:

var myDropDownListValues = $("#myDropDownList").multiselect("getChecked").map(function()
{
    return this.value;    
}).get();

It works for me :)

这个对我有用 :)

回答by notMyName

This got me the value and text of the selected optionsfor the jQuery multiselect.jsplugin:

这为我提供了jQuery multiselect.js插件的选定选项的值和文本:

$("#selectBox").multiSelect({
    afterSelect: function(){
        var selections = [];
        $("#selectBox option:selected").each(function(){
            var optionValue = $(this).val();
            var optionText = $(this).text();
            console.log("optionText",optionText);                
            // collect all values
            selections.push(optionValue);
        });

        // use array "selections" here.. 
    }
});   

very usefull if you need it for your "onChange" event ;)

如果您的“onChange”事件需要它,则非常有用;)

回答by Dulith De Costa

You could do like this too.

你也可以这样做。

<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
    <select id="selectDuration" name="selectDuration[]" multiple="multiple"> 
        <option value="1 WEEK" >Last 1 Week</option>
        <option value="2 WEEK" >Last 2 Week </option>
        <option value="3 WEEK" >Last 3 Week</option>
         <option value="4 WEEK" >Last 4 Week</option>
          <option value="5 WEEK" >Last 5 Week</option>
           <option value="6 WEEK" >Last 6 Week</option>
    </select>
     <input type="submit"/> 
</form>

Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.

然后从下面的 PHP 代码中进行多项选择。它相应地打印选定的多个值。

$shift=$_POST['selectDuration'];

print_r($shift);