Jquery adds "Selected" in an option

Asked

Viewed 30 times

0

I have the following code:

<select id="billing">
    <option value="485">Acre</option>
    <option value="486">Amapá</option>
    ...
</select>

When the user enters the zip code, the system automatically searches the address and inserts the data into the form. However, I need this Jquery to locate the value of the option and include Selected="Selected". Thank you for the force.

  • That’s not really how it works... just make a document.getElementById('billing').value = 486, for example

1 answer

1

Not having the rest of the code, it’s hard to give a functional example, but it should do what you need: $('#billing').val(seuValor);

function testar(){
  $('#billing').val('485');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="billing">
    <option value="" disabled selected hidden>Estado</option>
    <option value="485">Acre</option>
    <option value="486">Amapá</option>
</select>
<button onclick="testar()">Clique me</button>

  • I added a functional example, I hope you don’t mind :)

  • Thanks @Marceloboni for editing, it’s much better this way :)

Browser other questions tagged

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