Prevent a value from being selected in the dropdown

2

Is there any way to prevent a value from being selected in a dropdown? For example:

document.getElementById('teste').onchange = function (event){
  var valor = this.value;
  if(valor == 4){
    alert('esse valor não pode!');
    event.preventDefault();
    return false;
  }
}
<select id="teste">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

In the snippet above, if the value is 4, it should cancel the selection, and keep the value that was selected before. What is the right way to do this? Initially, I'm thinking of saving the value and selecting via javascript if I can not select a certain value. I accept solutions with or without jquery

    
asked by anonymous 05.10.2017 / 22:07

3 answers

2

Leave the option enabled for the user to select it, and wait for it to do so to display an alert saying they can not ... That's ugly! Only the alert is missing contain the "pegadinha do malandro!" words to complete the insult: \

The most elegant way is to simply disable the option:

<select>
    <option>Muito</option>
    <option>obrigado</option>
    <option>por</option>
    <option>serem</option>
    <option disabled>você não</option>
    <option>os</option>
    <option>melhores</option>
    <option>exemplos</option>
    <option>selecionáveis</option>
</select>

Simple, short and easy to do, understand and maintain.

    
05.10.2017 / 23:05
2

You can return to the original value using $ .data , which stores information in the DOM of the element itself. This prevents the use of global variables or field creation only to store this value. $ .Data, or $ (element) .data, works with key / value, like this:

$(document).ready(function(){

$("#teste").data('current', $("#teste").val()); // guarda o valor inicial do select com a chave "current"

$("#teste").on("change", function (event){

  var valor = $(this).val();
  if(valor == 4){
    alert('esse valor não pode!');
    $(this).val($.data(this, 'current')); // retorna ao valor inicial/anterior
    return false;
  }
   $(this).data('current', $(this).val()); // atualiza com o novo valor que foi possível selecionar
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="teste">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
    
05.10.2017 / 22:36
1

Using Vanilla.

document.getElementById('teste').onclick = function (event){
if(event.target.options) el = event.target.options[event.target.options.selectedIndex]; 
}
document.getElementById('teste').onchange = function (event){
	if(this.value == 4) el.selected = true;
}
<select id="teste">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
    
05.10.2017 / 22:48