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

问题描述 投票:38回答:5

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

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

谢谢

jquery html-select key-value
5个回答
83
投票

我假设你的意思是“关键”和“价值”:

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

如果是这样的话,这会让你获得“价值”:

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

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

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

24
投票

这有效:

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

8
投票
<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>

如果您选择了等等,则返回1,等等。


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

0
投票
$("#elementName option").text(); 

这将给出Combo-Box的选定文本。

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

这将在组合框中为选定值关联所选项目。

$("#elementName option").length;

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

注意:#elementName是组合框的id。

© www.soinside.com 2019 - 2024. All rights reserved.