What is the best way to select an option by text and not by value in jQuery?

10

I have a select and would like to select a value according to the text of another field that the user clicked on.

For example. When I click on a "p" tag with the text "April" I want to select the "April" text option in my select:

<select id="meses">
    <option value="0">Janeiro</option>
    <option value="1">Fevereiro</option>
    <option value="2">Março</option>
    <option value="3">Abril</option>
</select>

My tag p:

<p class="nomMes">Abril</p>

I wanted something like this:

var valMes = $('p.nomMes').text().trim();

$(document).on('click', 'p.nomMes', function(){
    $('#meses option[text='+valMes+']).prop('selected', true);
});

But the option [text =] does not work so what would be the most elegant way to do this, without having to loop through the select for example?

    
asked by anonymous 24.02.2014 / 15:34

3 answers

10

In this case I would use jQuery filter feature which will return the first result it encounters with the settings of the function you have determined.

Example:

$(document).ready(function () {
    // Armazena nome do mês que quer selecionar
    var mes = $('.nomMes').text().trim();
    // Guarda em opt o elemento que retornar do filtro que vai testar entre as
    // options possíveis
    var opt = $('#meses option').filter(function() {
        // testa entre as options qual delas tem o mesmo conteúdo que o desejado
        return $(this).text().trim() === mes;
    });

    // Redefine o atributo do elemento encontrado pra selecionado.
    opt.attr('selected', true);
});

DEMO

    
24.02.2014 / 15:44
4

You can use the contains selector of jQuery ... it is not exactly the request but solves the problem if the search domain has only different texts:

$("#meses option:contains('"+valMes+"')").prop('selected', true);

Example in jsfiddle

    
24.02.2014 / 16:40
0

You could assign value or text equal to text in option , like this:

<option value="Janeiro"> Janeiro </option>

or

<option value="0" text="Janeiro"> Janeiro </option>

You do not need to use contains .

$("#meses option[value="Janeiro"]').prop('selected', true);

or

$("#meses option[text="Janeiro"]').prop('selected', true);

I ran some tests and thus, without contains , the result is up to 80% faster.

    
03.10.2014 / 21:19