Reputation: 503
I am trying to valdate a drop down by checking to see that something other than the first option ("Choose one") is skipped
Logic: Is it true that the value is NOT "choose"? If so, return true (submit the form). I believe the logic requires me to test to see if the value is NOT the first option. My code seems correct, but I guess I am not doing the "!" operator correctly.
I have tried these versions of "If val is NOT string; but they didn't work.
if(val !== 'choose')
if(val != 'choose')
// Code example below
<form onsubmit="return validatedMenu()">
<select id="dropDown">
<option value="choose">Choose one...</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<input type="submit" value="select" />
</form>
<div>message here: <span id="mySpan"></span></div>
function validatedMenu() {
var dd = document.getElementById("dropDown");
var val = dd.options[dd.selectedIndex].value;
var txt = dd.options[dd.selectedIndex].text;
if(val != 'choose') {
document.getElementById("mySpan").innerHTML = "You must make a selection.";
}
else {
document.getElementById("mySpan").innerHTML = "Success! You chose " + txt;
return false;
}
return true;
}
Upvotes: 0
Views: 264
Reputation: 4755
You just have your logic flipped backwards. If val != 'choose'
, that means that the user HAS made a selection. However, in that if statement you're running the logic for when they have not. You just need to flip the contents of your if/else:
function validatedMenu() {
var dd = document.getElementById("dropDown");
var val = dd.options[dd.selectedIndex].value;
var txt = dd.options[dd.selectedIndex].text;
if(val != 'choose') {
document.getElementById("mySpan").innerHTML = "Success! You chose " + txt;
return true;
}
else {
document.getElementById("mySpan").innerHTML = "You must make a selection.";
}
return false;
}
However, if you for some reason wanted to have the success condition as the else and the failure condition as the if, you'll just need to reverse what you're evaluating in the if(), so that selecting the first option will cause it to be true:
function validatedMenu() {
var dd = document.getElementById("dropDown");
var val = dd.options[dd.selectedIndex].value;
var txt = dd.options[dd.selectedIndex].text;
if(val == 'choose') {
document.getElementById("mySpan").innerHTML = "You must make a selection.";
return false;
}
else {
document.getElementById("mySpan").innerHTML = "Success! You chose " + txt;
}
return true;
}
Upvotes: 3