Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get text of a selected option from the select element?

EDIT: The HTML and js bellow is a simplified version. Check out the jsfiddle link on the bottom of my post for full demonstration of my problem.


I have a select HTML element:

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

I want to get the label of a selected option with jQuery. This, however:

alert($("#foo option:selected").text());

Returns:

a
b
c

I want to get just, for example:

b

jsfiddle: http://jsfiddle.net/8KcYY/1/ (click on the "Vybrať značku" button).

like image 826
Richard Knop Avatar asked Dec 07 '22 22:12

Richard Knop


2 Answers

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

Try it yourself: http://jsfiddle.net/Nyenh/

Even simpler:

$('#foo').change(function(){
    var selected = $(this).find('option:selected');
    alert(selected.val() + ' ' + selected.text());
});

http://jsfiddle.net/qtRhQ/1/

like image 112
Kon Avatar answered Apr 01 '23 16:04

Kon


 $("#dropdownlistID").text();

This will show all positions in your "dropdownlist". To get only selected item use:

 $("#dropdownlistID").val();

Or try like

 $("#foo").find(":selected").text()

instead of

$("#foo option:selected").text()
like image 36
Anand Thangappan Avatar answered Apr 01 '23 16:04

Anand Thangappan