[英]JS Validation if dropdown value selected or not
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. 我正在尝试在我的JS中编写一个验证块来检查用户是否选择了一个值,如果未选择该值则弹出一条消息。
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! 谢谢!
If no option is selected, the select element's selectedIndex will be -1
. 如果未选择任何选项,则select元素的selectedIndex将为
-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. 仅当第一个选项具有selected属性时才会为true。 So either test against -1 or make the first option selected by default, eg
因此,要么针对-1进行测试,要么默认选择第一个选项,例如
<select name="dropdown" ...>
<option selected value="default">Please select an option
...
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.