How to find and select option with select-specific label with jQuery

Asked

Viewed 845 times

2

With jQuery, how do I change the label of an option, not value, example:

<select id="meuSelect">
    <option>[nao_selecionar_esse label]</option>
    <option>[SELECIONAR_esse label]</option>
    <option>[nao_selecionar_esse label]</option>
</select>
  • Would you have more options within select? Which event would trigger this change? Try to be more specific about what you need to ask the question

  • Yes, I tried that way var typePagtos = "[ALTERAR_ESSSE_LABEL]" $("#typofaturaPagtos"). val(typofaturaPagtos). change(); But it checks value, not label.

  • Post everything as you tried, working with jquery and options is complicated so, even more if you have more options and need to take a specific value to mark, otherwise you could have answered that you can use text() instead of val()...

2 answers

1

Use text

$(document).ready(function(){
      $('select option:nth-child(2)').text('alterado').attr('selected', 'true');
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select id="meuSelect">
        <option value='10'>[ALTERAR_ESSE_LABEL]</option>
        <option value='10'>[ALTERAR_ESSE_LABEL]</option>
        <option value='10'>[ALTERAR_ESSE_LABEL]</option>
    </select>

Obs: that nth-child on the dial is to catch the first select, not affecting others in the event of having more than one.

  • Now that I noticed an error, the code changes the label, I wanted to find the label equal to the value passed in . text(); and mark it as Selected ( . change(); )

  • edited the question with what you want

  • But it should not necessarily be option 2, because the list has 15 options, and when registering the user selects one, and when editing, he should select the option with the label that is in the database, it could be by value that is simple, but it is a client Procedure that cannot be changed.

  • Sorry I didn’t understand anything, be more objective, what you want to do?

1

You can do it this way:

$("select").find("option").html("SEU_TEXTO");

Or if you want this specific option can do so

$("select").find("option[value=10]").html("SEU_TEXTO");
  • 1

    This option worked for me, I adapted it. $("#typofaturaPagtos"). find("option"). html(typofaturaPagtos). change();

  • Now that I noticed an error, the code changes the label, I wanted to find the label equal to the value passed in . text(); and mark it as Selected ( . change(); )

  • in case you can do so $("select").find("option[value=10]").attr("selected","true")

Browser other questions tagged

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