<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.
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);
var id= "sel01";
$('#selectid option').each(function(){
if($(this).attr('id') == id){
$(this).attr('selected',true);
}
});
You can retrieve the element value using the ID and use the value for the jQuery val()
.
var elementId = 'sel01';
$("#mySelect").val($('#' + elementId).val());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With