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

Asked

Viewed 4,291 times

10

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

For example. By clicking a "p" tag with the "April" text 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=] doesn’t work so what would be the most elegant way to do it, without having to loop in select for example?

  • João, I know your question was about how to search the text, but if we are going to evaluate the performance it would not be better to assign for example the id in the tag <p> and fetch the value where the id is equal?

  • Yes, but it is an urgent implementation and due to the conditions that exist in the generation of the code by the server I would have to change in several places and in js only in one.

3 answers

10


In this case I would use the filter of jQuery which will return the first result it meets with the definitions of the function 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

  • What would be the "el" ?

  • It was unintentionally hehe, force of habit of not using jQuery, but in jQuery there was coming the "index" of iteration. If it was a filter of the Array.prototype.filter the first is the content of the iteration, second is the index and third is the array itself. Already in jQuery they pass the content as context of callback function.

  • It worked round. Thank you!

  • A pleasure friend :)

4

You can use the selector contains jQuery... is not exactly the request but solves the problem in case the search domain has only distinct texts:

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

Example in jsfiddle

  • This solution is pretty cool too. I will use it next time.

0

You could assign the value or text equal to the text in option, thus:

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

or

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

Ai need not use the 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.