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’s the right way to do this? Initially, I’m thinking of saving the value and selecting via javascript
if you cannot select a certain value.
I accept solutions with or without jquery
The way you thought is valid, besides having thousands of ways to do it, but basically, you’re thinking the right way
– Rafael Augusto
@Rafaelaugusto thought there was some way to cancel the event :(
– Artur Trapp
Can you explain why the value cannot be selected? Depending on the case you could give a 'disabled' in the <option>.
– Renato Diniz
I believe I haven’t, at least I’ve never used, but I could be wrong. Soon the Sergio appears here is concretized the answer.
– Rafael Augusto
@Renatodiniz is that depending on the options he has added in another listbox, certain values cannot be selected in the dropdown in question, and as it can change the values of the list at any time, I found it simpler to check the options of the list each
change
than to control theoption
which must be disabled or not– Artur Trapp
Why don’t you put one
disabled
option using theonchage
previous listbox? As @Renatodiniz proposed, it would be easier and even better.– Sam
Even if you want to do it this way that you want to do, which I think is valid too, I would suggest that when the person chooses option "4", instead of switching to the value that was selected before, switch to the first
option
same. I find this resource superfluous.– Sam
When the person selects the "4", gives the alert and everything and goes back to the first
option
withdocument.getElementById('teste').selectedIndex = 0;
. Simple and without many codes.– Sam