Reputation: 491
I am trying to write a validation block inside my JS to check if the user has selected a value or not and pop up a message if the value is not selected.
function validate(form) {
var success = true;
var message = "";
if (form.dropdown.selectedIndex == 0 ) {
form.save.disabled=true;
if (0 < message.length) {
message += "\n";
}
message += "dropdown value should be selected.";
}
if (0 < message.length) {
alert(message);
success = false;
}
return success;
}
When I click on Save button I call this function. I don't see errors in the logs. Can anyone tell me what am I doing wrongly here? Or can you guide me what is the correct method to validate if the user has selected a value before allowing to save?
Thanks!
Upvotes: 1
Views: 16914
Reputation: 147403
If no option is selected, the select element's selectedIndex will be -1
. It's recommended that one option is always set to selected, that way you know what the default selected option is (user agents may make the first option selected by default if you don't).
So the test:
if (form.dropdown.selectedIndex == 0 ) {
will only be true if the first option has the selected attribute. So either test against -1 or make the first option selected by default, e.g.
<select name="dropdown" ...>
<option selected value="default">Please select an option
...
</select>
Upvotes: 3