如果选中复选框,则需要 JQuery 验证选择
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6573487/
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
JQuery validation-select required if checkbox checked
提问by Howard Shaw
using jquery I want to make a selection from a select box required (ie it can't be left as the blank default) if a particular checkbox is ticked. My code:
使用 jquery 我想从所需的选择框中进行选择(即,如果选中特定复选框,则不能将其保留为空白默认值)。我的代码:
$(document).ready(function(){
$("#myForm").validate({
rules: {
myDropDown: {
required: {
depends: function(element) {
return $("#myCheckbox:checked")
}
}
}
}
})
})
The html:
html:
<input type="checkbox" name="myCheckbox" id="myCheckbox" value="1">
<select name="myDropDown" id="myDropDown">
<option value="" selected></option>
<option value="1">Choice 1</option>
<option value="2">Choice 2</option>
<option value="3">Choice 3</option>
</select>
Not only is the code not working it's throwing out the jquery tabs that I have as the next section of javascript.
代码不仅不起作用,而且还丢弃了我作为 javascript 下一部分的 jquery 选项卡。
Any advice appreciated.
任何建议表示赞赏。
Edit: Now that I've sorted out all my brackets the behaviour now is that it's making the select box a required field whether or not the checkbox is checked - ie the depends part is not working. Other javascript on the page is now working ok.
编辑:现在我已经整理了我所有的括号,现在的行为是,无论是否选中复选框,它都会使选择框成为必填字段 - 即依赖部分不起作用。页面上的其他 javascript 现在工作正常。
采纳答案by Mahesh KP
Please try like this
请尝试这样
$(document).ready(function(){
$("#myForm").validate({
rules: {
myDropDown:{
required: function (element) {
if($("#myCheckbox").is(':checked')){
var e = document.getElementById("myDropDown");
return e.options[e.selectedIndex].value=="" ;
}
else
{
return false;
}
}
}
}
});
});
回答by elle
it should be able to work just like that:
它应该能够像这样工作:
rules : {
myDropDown:{required:"#myCheckbox:checked"}
}
回答by Koen den Braven
This works like a charm
这就像一个魅力
inputname:
{
required: function(){
if($("select[name=inputname]").val() == 1){
return true;
}
else
{
return false;
}
}
}
You can edit the inputname to yours prefered.
您可以根据自己的喜好编辑输入名称。
To change it to input field, you can change the select part to input
要将其更改为输入字段,您可以将选择部分更改为输入
回答by Nicola Peluchetti
I don't know what plugin you are using, but
我不知道你用的是什么插件,但是
return $("#myCheckbox:checked")
returns a Jquery object if your checkbox is checked. I think it would be more correct to do:
如果您的复选框被选中,则返回一个 Jquery 对象。我认为这样做更正确:
return $("#myCheckbox").is(':checked')
which returns true or false.
返回真或假。
Maybe this has nothing to to with your problem
也许这与您的问题无关