Multiselect,Jquery:检查我的多重选择是否应该选择至少一个选项

嗨,我会总结一下我的问题,希望你能理解。

主要目标:在点击选择按钮之前检查是否至少选择了其中一个选项。 否则,如果单击“选择”按钮而未选择至少一个选项,则会显示“请选择至少一个选项”的消息。

目的:我在其他代码中有理由需要一个选择按钮,而不是只选择多个选择而不需要按钮。

表单如下所示:

在此处输入图像描述

简单的HTML代码:

// My Select Id is monthlymonth
October November December
/My Select button, Id is monthsubmit.

现在我的JQuery:

 $("#monthsubmit").unbind('click').bind('click', function() { if (// code that checks if no options is selected at least one) { alert('Please choose at least one month'); } else { // my other codes } }); 

希望这可以帮助你if ($('#monthlymonth').get(0).selectedIndex == -1)

 $("#monthsubmit").on('click', function() { if ($('#monthlymonth').get(0).selectedIndex == -1) { alert('Please choose at least one month'); } else { // my other codes } }); $("#clear").on('click', function() { $("#monthlymonth option:selected").removeAttr("selected"); }); 
  

如果您使用的是Jquery,检查输入值的最佳方法是使用“val()”函数。 如果未选择任何内容,则返回null值。

这是一个例子:

 $("#monthsubmit").unbind('click').bind('click', function() { if (!$("#monthlymonthdiv").val()) { alert('Please choose at least one month'); } else { // my other codes } }); 
  

试试简化版。

 $("#monthsubmit").click(function(){ if (!$("#monthlymonth option:selected").length) { alert('Please choose at least one month'); } }); $("#clear").click(function(){ $("#monthlymonth option:selected").removeAttr("selected"); });