使用 jQuery 获取组合框的选定键/值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5714196/
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-26 19:42:00  来源:igfitidea点击:

Get selected key/value of a combo box using jQuery

jqueryhtml-selectkey-value

提问by Amit

Please, how can I get the selected key and value of a HTML select combo box using jQuery?

请问,如何使用 jQuery 获取 HTML 选择组合框的选定键和值?

$(this).find("select").each(function () {
    if ($.trim($(this).val()) != '') {
        searchString += $.trim($(this).val()) + " "; //This gives me the key. How can I get the value also?
    }
});

Thanks

谢谢

回答by David Tang

I assume by "key" and "value" you mean:

我假设“键”和“值”是指:

<select>
    <option value="KEY">VALUE</option>
</select>

If that's the case, this will get you the "VALUE":

如果是这种情况,这将为您提供“VALUE”:

$(this).find('option:selected').text();

And you can get the "KEY" like this:

你可以像这样得到“KEY”:

$(this).find('option:selected').val();

回答by Anand Thangappan

This works:

这有效:

<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />

$('#button').click(function() {
    alert($('#foo option:selected').text());
    alert($('#foo option:selected').val());
});

回答by Alborz

<select name="foo" id="foo">
 <option value="1">a</option>
 <option value="2">b</option>
 <option value="3">c</option>
  </select>
  <input type="button" id="button" value="Button" />
  });
  <script> ("#foo").val() </script>

which returns 1 if you have selected a and so on..

如果您选择了一个等等,它会返回 1..

回答by Calum

$(this).find("select").each(function () {
    $(this).find('option:selected').text();
});

回答by Laxman G

$("#elementName option").text(); 

This will give selected text of Combo-Box.

这将给出组合框的选定文本。

$("#elementName option").val();

This will give selected value associated selected item in Combo-Box.

这将在组合框中给出与选定项目相关联的选定值。

$("#elementName option").length;

It will give the multi-select combobox values in the array and length will give number of element of the array.

它将给出数组中的多选组合框值,长度将给出数组元素的数量。

Note:#elementNameis id the Combo-box.

注意#elementName是组合框的 ID。