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

Ami*_*mit 40 jquery html-select key-value

请问,如何使用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?
    }
});
Run Code Online (Sandbox Code Playgroud)

谢谢

Dav*_*ang 87

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

<select>
    <option value="KEY">VALUE</option>
</select>
Run Code Online (Sandbox Code Playgroud)

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

$(this).find('option:selected').text();
Run Code Online (Sandbox Code Playgroud)

你可以像这样获得"KEY":

$(this).find('option:selected').val();
Run Code Online (Sandbox Code Playgroud)

  • Bala,你可以使用,$(this).find('option:selected').val(); (2认同)

Ana*_*pan 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());
});
Run Code Online (Sandbox Code Playgroud)


Alb*_*orz 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>
Run Code Online (Sandbox Code Playgroud)

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