Selecting the VALUE of a select with javascript or jquery [duplicate]

1

Well, I have the following problem:

I need to select the value of a select in 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 select , when it is different from the first option, this first option given as default will be excluded from html

    
asked by anonymous 25.10.2016 / 14:08

3 answers

2

Just add some id 's, and a value to the field you want to delete, if the select does not have the value 0 for example, then it removes the same, which has 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();
   };
});
    
25.10.2016 / 14:42
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>
    
25.10.2016 / 14:33
3

Pure Javascript example:

<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 the script only):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="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>
    
25.10.2016 / 14:40