Jquery-traversing: select & # 8594; option & # 8594; text

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

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

here is the html:

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

here are a few attempts

 $('#id option:eq("'+lista+'")').attr('selected','selected') $("#id option[text='"+lista+"']").attr('selected','selected') 
+6
source share
5 answers

Instead of scrolling through each one, you can try the following:

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

or

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

It works just as well. It just depends if your lista variable needs to be exact or partial.

+7
source

There is nothing wrong with what you have, jQuery will do more or less of the same under the hood.

You can use filter() if you want to link all this together:

 var lista = 'example 1'; $('#id option').filter(function () { return $(this).text() == lista; })[0].selected = true; 

:contains may work for you, but it works like a wildcard, for example. cat will match the category:

 var lista = 'example 1'; $('#id option:contains(' + lista + ')')[0].selected = true; 
+2
source

Your method is quite effective, but a little more can be done like this:

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

This uses its own properties, so it will be faster.

  • .text property provides the text content of the <option> element

  • .selected sets the selected property

  • return false; will break the loop if it is selected, so it does not need to continue

+2
source

This should work:

 $("#id option").attr('selected', function() { return this.innerHTML === lista; }); 
+1
source

I'm probably too late.

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

This is approximately 97% faster than

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

check performance log http://jsperf.com/selector-performance-00000

0
source

All Articles