Selecting the VALUE of a select with javascript or jquery

Asked

Viewed 585 times

1

Well, I have the following problem:

I need to select the value of a select in the html to execute a loop if in javascript or jquery, how to do ?

<select class="input">
    <option default disabled="disabled">--</option>
    <option value="">TESTE1</option>
    <option value="">TESTE2</option>
    <option value="">TESTE3</option>
</select>

in this case, the value of the select, when different from the first option, the first option given as default will be excluded from html

  • 1

    thanks, I will make a proper response to the problem, so it can end up facilitating for staff

3 answers

3

You can solve it like this:

var selectTeste = document.getElementById('selectTeste');
if (selectTeste.selectedIndex !== 0) {
  selectTeste.removeChild(selectTeste.firstElementChild);
}
<select class="input" id="selectTeste">
    <option default disabled="disabled">--</option>
    <option value="TESTE1">TESTE1</option>
    <option value="TESTE2">TESTE2</option>
    <option value="TESTE3">TESTE3</option>
</select>

3

Example in pure Javascript:

<select id="select">
  <option disabled selected>Escolha...</option>
  <option value="aaa">AAA</option>
  <option value="bbb">BBB</option>  
  <option value="ccc">CCC</option>  
</select>

<script>
  document.querySelector('#select').onchange = function() {
    if(this.querySelector(':disabled')) {
      this.querySelector(':disabled').remove();
    }
    var selectedValue = this.value;
    console.log(selectedValue);
  }
</script>

Example with jQuery (changes only script):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select">
  <option disabled selected>Escolha...</option>
  <option value="aaa">AAA</option>
  <option value="bbb">BBB</option>  
  <option value="ccc">CCC</option>  
</select>

<script>
  $('#select').change(function() {
    $(this).find(":disabled").remove();
    var selectedValue = this.value;
    console.log(selectedValue);
  });
</script>

2


Just add a few id's, and a value to the field you want to delete if select does not have the value 0 for example, then it removes the same, which has to id 'default-selecionado'

HTML

<select class="input" id="selecionar-categoria">
    <option default disabled="disabled" id="default-selected" value="0">--</option>
    <option value="">TESTE1</option>
    <option value="">TESTE2</option>
    <option value="">TESTE3</option>
</select>

Jquery

$("#selecionar-categoria").on('change', function(){
   if($(this).val() != '0'){
     $("#default-select").remove();
   };
});

Browser other questions tagged

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