Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 522
Amit Avatar asked Apr 19 '11 09:04

Amit


2 Answers

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(); 
like image 135
David Tang Avatar answered Sep 19 '22 09:09

David Tang


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()); }); 
like image 20
Anand Thangappan Avatar answered Sep 19 '22 09:09

Anand Thangappan