遍历<select>选项


202

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

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

Answers:


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

2
它很奇怪,这应该可以工作,但是由于某种原因它对我
不起作用

14
它应该是$(this).val()而不是IT ppl所说的this.value。
Thihara 2012年

只有IT PPL的答案对我
有用

1
获取值和文本分别应为$(this).val()和$(this).text()
Amit Bhagat 2014年

5
@AmitKB-最好使用本机DOM方法提取文本和值。1)简短一些2)避免构造两个新的jQuery对象。
karim79

79

这对我有用

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

5
如果您将其存储$(this)在变量中,则效率会更高,例如var $this = $(this); $this.text(); $this.val();...etc.
Liam

25

也可以使用带有索引和元素的参数化的每个参数。

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

17

对于追随者而言,这是必需的,非jquery的方式,因为google似乎将所有人发送到这里:

  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

您也可以尝试这样。

您的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);
});

要么

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

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


1

如果您不需要Jquery(并且可以使用ES6)

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

不鼓励仅使用代码的答案。请添加一些有关如何解决问题或与现有答案有何不同的解释。From
尼克

1

在没有jQuery的情况下,已经提出的答案的另一个变体。

Object.values(document.getElementById('mySelect').options).forEach(option => alert(option))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.