javascript 如何验证多选下拉列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13892711/
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 20:04:39  来源:igfitidea点击:

How to validate a multiselect Dropdown?

javascripthtmlmulti-select

提问by Bruno Andrade

So the situation is this: I'm creating a dropdown box using the jquery.multiselect plugin on a form, but I need to check if there's some value selected, if there isn't one or more values selected I wanna throw a alert or something when some one tries to submit the form.

所以情况是这样的:我正在使用表单上的 jquery.multiselect 插件创建一个下拉框,但我需要检查是否选择了某个值,如果没有选择一个或多个值,我想发出警报或当有人试图提交表单时发生的事情。

The HTML Code

HTML代码

<form id="RNA" name="RNA">
<select size="5" name="sampleMut[]" multiple="multiple" id="sampleMut">

 <option value="41" >41</option>
  <option value="48" >48</option>
  <option value="65" >65</option>
  <option value="102" >102</option>

</select>
</form>

The JavaScript Code

JavaScript 代码

$(function(){
 $("#sampleMut").multiselect(); 
});

jQuery version 1.8.3

jQuery 版本1.8.3

jquery.multiselect 1.13

jquery.multiselect 1.13

回答by karaxuna

Try this:

试试这个:

$(function(){
    $('form').submit(function(){
         var options = $('#sampleMut > option:selected');
         if(options.length == 0){
             alert('no value selected');
             return false;
         }
    });
});

Fiddle: http://jsfiddle.net/aDxu8/1/

小提琴:http: //jsfiddle.net/aDxu8/1/

回答by Dávid Szabó

With this you can get the amount of the selected options.

有了这个,您可以获得所选选项的数量。

$("#sampleMut option:selected").length;