[英]jquery how to make sure that the user has selected a value for all select menus on a form
i have a form with multiple select menus i want to make sure on submit that a user selected a value for each select menu how can i do that with jquery ? 我有一个带有多个选择菜单的表单,我想确保在提交时用户为每个选择菜单选择了一个值,该如何使用jquery做到这一点? i tried something like
我尝试过类似的东西
var form = $('myform');
if($(form ).find('select').length != $(form).find('select:option[selected="selected"]').length ) {
alert('wrong please make sure to select all select menu');
}
but no luck 但没有运气
please help 请帮忙
Thank you 谢谢
The form object has already been created.I removed the $()
function from the form variables in the if
statement. 表单对象已经创建。我从
if
语句的表单变量中删除了$()
函数。 You should also be using an identifier for myform
. 您还应该为
myform
使用标识符。
var form = $('form#myform');
if(form.find('select').length != form.find('select:option[selected="selected"]').length ) {
alert('wrong please make sure to select all select menu');
}
I recommend you prefix your form
var with a $
to note that you are already using a jquery object. 我建议你的前缀
form
变种与$
要注意,你已经在使用jQuery对象。
Example: 例:
var $form = $('form#myform');
if($form.find('select').length != $form.find('select:option[selected="selected"]').length ) {
alert('wrong please make sure to select all select menu');
}
By default select element's first option is selected if none of the options have selected
attribute, so your selector will not work which is looking for selected
attribute in the option element. 默认情况下,如果所有选项都没有
selected
属性,则选择元素的第一个选项处于selected
,因此您的选择器将不起作用,该选项在选项元素中查找selected
属性。 Also if the id
of the form is myform
then you should use #myform
to find it. 另外,如果表单的
id
为myform
,则应使用#myform
进行查找。 Try this. 尝试这个。
var $form = $('#myform');
if($form.find('select').length != $form.find('select:option:selected').length ) {
alert('wrong please make sure to select all select menu');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.