javascript – What's the best way to select an option by text and not by value in jQuery?

Question:

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

For example. When clicking on a tag "p" with the text "April" I want to select the text option "April" 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 p tag:

<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 option[text=] doesn't work so what would be the most elegant way to do this, without having to loop the select for example?

Answer:

In this case I would use jQuery 's filter feature which will return the first result it finds with the function definitions you 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

Scroll to Top