通过<select>选项</select>进行迭代

时间:2010-06-01 13:30:35

标签: jquery

我在HTML中有一个<select>元素。此元素表示下拉列表。我试图了解如何通过JQuery迭代<select>元素中的选项。

如何使用JQuery显示<select>元素中每个选项的值和文本?我只想在alert()框中显示它们。

9 个答案:

答案 0 :(得分:317)

$("#selectId > option").each(function() {
    alert(this.text + ' ' + this.value);
});

答案 1 :(得分:77)

这对我有用

$(function() {
    $("#select option").each(function(i){
        alert($(this).text() + " : " + $(this).val());
    });
});

答案 2 :(得分:22)

也可以使用参数化的索引和元素。

$('#selectIntegrationConf').find('option').each(function(index,element){
 console.log(index);
 console.log(element.value);
 console.log(element.text);
 });

//这也可行

$('#selectIntegrationConf option').each(function(index,element){
 console.log(index);
 console.log(element.value);
 console.log(element.text);
 });

答案 3 :(得分:9)

对于粉丝来说,这是必要的,非jquery的方式,因为谷歌似乎把所有人都送到了这里:

  var select = document.getElementById("select_id");
  for (var i = 0; i < select.length; i++){
    var option = select.options[i];
    // now have option.text, option.value
  }

答案 4 :(得分:3)

您也可以尝试这样做。

您的HTML代码

<select id="mySelectionBox">
    <option value="hello">Foo</option>
    <option value="hello1">Foo1</option>
    <option value="hello2">Foo2</option>
    <option value="hello3">Foo3</option>
</select>

JQuery代码

$("#mySelectionBox option").each(function() {
    alert(this.text + ' ' + this.value);
});

OR

var select =  $('#mySelectionBox')[0];

  for (var i = 0; i < select.length; i++){
    var option = select.options[i];
    alert (option.text + ' ' + option.value);
  }

答案 5 :(得分:1)

$.each($("#MySelect option"), function(){
                    alert($(this).text() + " - " + $(this).val());                    
                });

答案 6 :(得分:1)

没有jQuery的已经提出的答案的另一种形式。

Object.values(document.getElementById('mySelect').options).forEach(option => alert(option))

答案 7 :(得分:0)

如果你不想要Jquery(并且可以使用ES6)

for (const option of document.getElementById('mySelect')) {
  console.log(option);
}

答案 8 :(得分:0)

尝试了几个代码之后,仍然无法正常工作,我去了select2.js的官方文档。 这里的链接: https://select2.org/programmatic-control/add-select-clear-items

从中清除选择select2 js的方法是:

$('#mySelect2').val(null).trigger('change');
相关问题