Debaprasad Jana
Debaprasad Jana

Reputation: 185

How to get the value of a select box element by its option in javascript?

My select box is as follows:

<select id='list'>
    <option value='1'>A</option>
    <option value='2'>B</option>
    <option value='3'>C</option>
</select>

I want to get the value of option - B without selecting it.

With jQuery I can do the opposite i.e get the text when I know the value through following:

$("#list option[value='2']").text();

But I want the reverse. I tried with following but not working:

 $("#owner option['B']").val();  

How can I do this?

Upvotes: 1

Views: 149

Answers (6)

jb10210
jb10210

Reputation: 1176

If you wanted to get the element by position, you can do this:

$('#list').children().eq(1).val();

Upvotes: -1

Amir Ismail
Amir Ismail

Reputation: 3883

Try this script

  $('#list option:contains("B")').prop('value') //jquery 1.6 or later

oR

$('#list option:contains("B")').attr('value');

Upvotes: 0

Jignesh Rajput
Jignesh Rajput

Reputation: 3558

try this

var b = $("#list").find('option:contains("B")').val();

see here : http://jsfiddle.net/MxpTZ/1/

Upvotes: 0

Richard Dalton
Richard Dalton

Reputation: 35803

You can use .filter to get the right option element:

$("#list option").filter(function() {
    return $(this).text() == "B";
}).val();

http://jsfiddle.net/JWjKf/

Upvotes: 1

Christofer Eliasson
Christofer Eliasson

Reputation: 33875

You can use the :contains(text) selector, to only get the elements that contain certain text:

$("#list option:contains('B')").val();

Upvotes: 2

user229044
user229044

Reputation: 239541

Use the :contains selector.

Assuming "owner" really is the ID of your <select> (it's "list" in your example), you can use:

 $("#owner option:contains('B')").val() // 2

Upvotes: 4

Related Questions