javascript JS 验证是否选择了下拉值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12521983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:25:54  来源:igfitidea点击:

JS Validation if dropdown value selected or not

javascriptdrop-down-menu

提问by smiley

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!

谢谢!

回答by RobG

If no option is selected, the select element's selectedIndexwill 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).

如果未选择任何选项,则选择元素的selectedIndex将为-1。建议始终将一个选项设置为selected,这样您就知道默认选择的选项是什么(如果您不这样做,用户代理可能会默认选择第一个选项)。

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.

仅当第一个选项具有 selected 属性时才为真。因此,要么针对 -1 进行测试,要么默认选择第一个选项,例如

<select name="dropdown" ...>
  <option selected value="default">Please select an option
  ...
</select>