10
<select id="mySelect"> <option id="sel01" value="some value">some value</option> <option id="sel02" value="some other value">some other value</option> <option id="sel03" value="maybe me">maybe me</option> <option id="sel04" value="and another one">and another one</option> </select> 

I would like to select an option with use of jQuery, but not by value:

$("#mySelect").val(1); 

but by elements id.

Thanks for an answer.

0

7 Answers 7

12

You can use prop method.

var id = 'sel02'; $('#mySelect option').filter(function(){ return this.id === id }).prop('selected', true); 

or:

$('#' + id).prop('selected', true); 

Or if you want to select an option based on it's index, you can use eq method:

$('#mySelect option').eq(1).prop('selected', true); 
Sign up to request clarification or add additional context in comments.

Comments

3
 var id= "sel01"; $('#selectid option').each(function(){ if($(this).attr('id') == id){ $(this).attr('selected',true); } }); 

Comments

1

You can retrieve the element value using the ID and use the value for the jQuery val().

var elementId = 'sel01'; $("#mySelect").val($('#' + elementId).val()); 

3 Comments

Love Your way, but "undefined" was first withh his method. Thanks.
@MarcinBobowski It's up to you to pick which solution you like better :)
The best thing is the ability to learn all the ways and understand them :)
1

If you want to select the option:

$('#mySelect option#sel02').prop('selected',true); 

if you want to get the selected option id's value:

$('#mySelect option#sel02').val(); 

Comments

1

Try this syntax,

$('select option:selected').attr('id'); 

check here, it will select the option based on the text value.

Comments

0

Like this. Just change the number in eq(0)

$("#mySelect").val($("#mySelect").children().eq(0).val()); 

Comments

0

I don't know the context but this worked for me when I needed to get data from json and make the option of that specific combo box selected:

$("#mySelect option[id='" + someVariable + "']").attr('selected', 'selected'); 

1 Comment

oops, sorry about that :(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.