jQuery 验证jquery中的下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5369764/
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
Validate dropdown list in jquery
提问by sanjeev
I have one dropdown in html and i want to validate it using jquery.
我在 html 中有一个下拉列表,我想使用 jquery 验证它。
Please select your rating * :
<select id="myDropdown">
<option value="">-Please Select-</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
My Jquery code is like
我的 Jquery 代码就像
if ($('#myDropdown option:selected').length == 0)
{
alert("Please select anyone");
}
What I need is if any value is not selected and it remains like -Please Select- and if the user press submit button, then an alert or any appropriate message needs to be displayed Please help
我需要的是如果没有选择任何值并且它仍然像 -请选择 - 如果用户按下提交按钮,则需要显示警报或任何适当的消息请帮助
回答by Jared Farrish
mydropdown = $('#myDropdown');
if (mydropdown.length == 0 || $(mydropdown).val() == "")
{
alert("Please select anyone");
}
See Notebelow. Also, you don't need the option:selected
(as per Sly's original answer).
请参阅下面的注释。此外,您不需要option:selected
(根据 Sly 的原始答案)。
On this fiddle, try selecting another value, then try to select the -Please Select-
option. You will see the alert()
.
在这个小提琴上,尝试选择另一个值,然后尝试选择该-Please Select-
选项。您将看到alert()
.
http://jsfiddle.net/userdude/aS2AM/
http://jsfiddle.net/userdude/aS2AM/
EDIT
编辑
NOTE: The length test is doing nothing, since it will always report 1, as at least one option is always selected (and your selector is always selecting at least one option, unless the select has no options). I have removed that in this update to the fiddle and code below:
注意:长度测试什么都不做,因为它总是报告 1,因为总是选择至少一个选项(并且您的选择器总是选择至少一个选项,除非选择没有选项)。我已在此更新中删除了下面的小提琴和代码:
http://jsfiddle.net/userdude/LdN6c/3/
http://jsfiddle.net/userdude/LdN6c/3/
You're not capturing the form submit event.
您没有捕获表单提交事件。
$(document).ready(function() {
$('#myForm').submit(function(e){ // <<< This selector needs to point to your form.
if ($('#myDropdown').val() == "") {
alert("Please select anyone");
e.preventDefault();
return false;
}
});
});
Note the #myForm
needs to select your actual form element that contains the selected element.
请注意#myForm
需要选择包含所选元素的实际表单元素。
See in action here: http://jsfiddle.net/userdude/LdN6c/1/
在此处查看操作:http: //jsfiddle.net/userdude/LdN6c/1/
回答by Sylvain Guillopé
jQuery(function($) {
$('#myForm').submit(function(e) {
if ($('#myDropdown').val() == '') {
e.preventDefault();
alert("Please select anyone");
}
});
});
- Edited with form submit event handler
- 使用表单提交事件处理程序进行编辑