How to update select with jQuery

Asked

Viewed 1,184 times

0

Hello.
I have a select

<div class="seletor">
   <select name="numeros" id="numeros">
      <option value="1" selected="selected">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
      <option value="6">6</option>
   </select>
   <span class="custom-select">1</span>
</div>

And I wanted to know how to select another value using jQuery?

  • Could explain better?

  • So in this select this selects option 1 right? And I need to select another option using jQuery. I tried $("#numbers"). val("1"); but it did not work

  • I put in the answer, see if it’s what you need :D

2 answers

2


You can use the .val() directly on select:

$('#selectValue').click(function (){ 
  $('#numeros').val($('#valor').val());
  $('.custom-select').text($('#numeros').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="seletor">
   <select name="numeros" id="numeros">
      <option value="1" selected="selected">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
      <option value="6">6</option>
   </select>
   <span class="custom-select">1</span>
</div>
<br>
Digite o valor: <input type="text" id="valor">
<input type="button" id="selectValue" value="Selecionar" /><br>

0

$('select option[value="2"]').attr({ selected : "selected"});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
        <option value="1" selected>1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>

Browser other questions tagged

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