Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery-traversing: select -> option -> text

I want to compare a variable with a select -> option -> text selected in order to change the "selected" attrib, here is my code, it works but I think is not the best way to write it, excuse my English, I used google translate for help hehehehe :

var lista = 'example 1'; 
$("#id option").each(function(){
  if($(this).text() == lista){
    $(this).attr('selected','selected');
  }
});

here's the html:

<select id="id" >
  <option value="0" >example 1</option>
  <option value="1" >example 2</option>
</select>

here's a few attempts

$('#id option:eq("'+lista+'")').attr('selected','selected')

$("#id option[text='"+lista+"']").attr('selected','selected')
like image 880
kakomerengue Avatar asked Feb 15 '11 20:02

kakomerengue


1 Answers

Instead of looping through each, you can try this:

var lista = 'example 1'; 
$('#id option:contains(' + lista + ')').attr('selected', true);

or

$('#id option:[text="' + lista + '"]').attr('selected', true);

Works just as well. It just depends if your variable lista will need to be an exact match or just a partial one.

like image 96
Victor Avatar answered Sep 21 '22 23:09

Victor