Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - set select index by elements id

<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.

like image 274
Marcin Bobowski Avatar asked Jan 14 '13 11:01

Marcin Bobowski


3 Answers

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);
like image 112
undefined Avatar answered Oct 16 '22 05:10

undefined


   var id= "sel01";

    $('#selectid option').each(function(){
        if($(this).attr('id') == id){
           $(this).attr('selected',true);
         }
    });
like image 31
THE ONLY ONE Avatar answered Oct 16 '22 05:10

THE ONLY ONE


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

var elementId = 'sel01';
$("#mySelect").val($('#' + elementId).val());
like image 26
Konstantin Dinev Avatar answered Oct 16 '22 06:10

Konstantin Dinev