Javascript“多重选择”选择框验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4794380/
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
Javascript "MULTIPLE Selection" Select box validation?
提问by OM The Eternity
I Have a Multiple selection select box. I need it to be validated using javascript, so that it should prompt to select atleast one value.
我有一个多选选择框。我需要使用 javascript 对其进行验证,以便它应提示选择至少一个值。
Below is the multiple select box I Have.
下面是我有的多选框。
<select name="usrgrp[]" multiple="multiple" size="3">
<option value="11">abc</option>
<option value="12">def</option>
<option value="13">ghi</option>
</select>
Please help me to write the validation javascript for this select box.
请帮我为这个选择框编写验证javascript。
回答by RoToRa
if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
  alert("Please select an item.");
}
回答by Yoesoff
the easiest way is use ! :
最简单的方法是使用!:
   if (!$('select').val())
    {
         //fail       
    }
回答by McStretch
I would start with the Validationdocs. If you find the need to validate more than just that field (perhaps you're building a form?), then using the Validation pluggin will help you much more than hacking together individual rules.
我将从验证文档开始。如果您发现需要验证的不仅仅是该字段(也许您正在构建一个表单?),那么使用验证插件对您的帮助不仅仅是将单个规则组合在一起。
Give it a shot, it's well written and contains many examples.
试一试,它写得很好,包含很多例子。

