Monday, May 20, 2024
122
rated 0 times [  125] [ 3]  / answers: 1 / hits: 16742  / 12 Years ago, thu, september 20, 2012, 12:00:00

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!


More From » drop-down-menu

 Answers
11

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>

[#82982] Wednesday, September 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devonw

Total Points: 311
Total Questions: 116
Total Answers: 111

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;