Amit
Amit

Reputation: 7035

Get selected key/value of a combo box using jQuery

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

$(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

Upvotes: 44

Views: 200042

Answers (5)

Tam
Tam

Reputation: 3987

$("#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:#elementName is id the Combo-box.

Upvotes: 2

David Tang
David Tang

Reputation: 93664

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":

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

And you can get the "KEY" like this:

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

Upvotes: 100

Alborz
Alborz

Reputation: 2043

<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..

Upvotes: 9

Anand Thangappan
Anand Thangappan

Reputation: 3106

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

Upvotes: 25

Calum
Calum

Reputation: 5316

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

Upvotes: 4

Related Questions