Validate value of a select

Asked

Viewed 72 times

1

<label>Itinerário</label>
<select id="itinerario" name="itinerario" class="form-control form-control-sm" required readonly>
    <option value="" selected>Selecione um itinerário</option>
</select>

JS:

if($('#itinerario :selected').text() == ""){
    alert('Elemento vazio!');
} 

I am trying to make the above code but it does not recognize the value, I need that when it is selected at that value="" empty, appear the Alert.

  • And when that if is executed?

  • When loading the page it already valid.

  • Are you using jQuery? If yes, it would be cool if you [Edit] the question and add the tag [tag:jquery].

1 answer

1

Use the function to val() and the event change jquery:

See the code below:

function validarSelect(){
  if(!$('#itinerario').val()){
    alert('Elemento vazio!');
  }
}

$(document).ready(function(){
  $('#itinerario').on('change', function(){
    validarSelect();
  });
 validarSelect();


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



<label>Itinerário</label>
<select id="itinerario" name="itinerario" class="form-control form-control-sm" required readonly>
    <option value="" selected>Selecione um itinerário</option>
    <option value="2" >Opção 2</option>
</select>

  • You could use $('#itinerario').on('change', validarSelect); since the function does not use any of its arguments...

  • Correct, thank you.

Browser other questions tagged

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