Javascript或Jquery来验证一组单选按钮?

Javascript或Jquery来验证一组单选按钮?,javascript,jquery,validation,radio-button,Javascript,Jquery,Validation,Radio Button,如何使用javascript或jquery获得以下内容的条件验证: 如果我选择“是”,我是素食者。我必须选择素食者 如果我选择“否”,我就不是素食者。我必须选择非素食者 <div> <input name="Vegetarian" type="radio" value="1">Yes <input name="Vegetarian" type="radio" value="0">No </div> .. <input name="Veggie

如何使用javascript或jquery获得以下内容的条件验证:

如果我选择“是”,我是素食者。我必须选择素食者 如果我选择“否”,我就不是素食者。我必须选择非素食者

<div>
<input name="Vegetarian" type="radio" value="1">Yes
<input name="Vegetarian" type="radio" value="0">No
</div>
..
<input name="Veggie" type="radio" value="veggieburger">Veggie Burger
<input name="Veggie" type="radio" value="fruit">Fruit
<input name="Veggie" type="radio" value="tofu">Tofu
<input name="Veggie" type="radio" value="salad">Salad
...
<input name="NonVeggie" type="radio" value="hamburger">Hamburger
<input name="NonVeggie" type="radio" value="chicken">Chicken
<input name="NonVeggie" type="radio" value="fish">Fish
<input name="NonVeggie" type="radio" value="turkey">Turkey

对
不
..
素食汉堡
果
豆腐
沙拉
...
汉堡包
鸡
鱼
土耳其

在没有尝试任何东西的情况下简单地询问解决方案,在这里不会得到太多回应。所以我不会为你做你的工作

我会给你指出正确的方向

单击第一组时,可以使用onClick事件启用/禁用一组单选按钮,强制用户从正确的组中选择条目

查看jQuery站点上的文档-实际上很容易掌握一些窍门


我相信您希望根据素食者选项选择显示/隐藏这些选项。试试这个

$('input[name=Vegetarian]').click(function(){
    $('input[name=Veggie]').parent().toggle(this.value == "1");
    $('input[name=NonVeggie]').parent().toggle(this.value != "1");
});

要验证相应的食物,请尝试以下操作:

var name = $('input[name=Vegetarian]').val() == '1' ? 'Veggie':'NonVeggie';

return $('input[name='+ name +']').is(':checked');
试试这个:

$("#submit").click(function() {
    var isVegetarian = $("input[name='Vegetarian']:checked").val() == "1";

    if (isVegetarian && $("input[name='Veggie']:checked").length == 0) {
        alert("Please select a vegetarian option");
    }
    else if (!isVegetarian && $("input[name='NonVeggie']:checked").length == 0) {
        alert("Please select a non-vegetarian option");
    }
});

如果你的网站上有各种各样的表单,我建议你使用。如果这个表单是一次性的,那么这个方法就足够了。

您可以使用jQuery


谢谢Rory的例子!谢谢sinsedrix的例子!你问的是验证,而不是隐藏一些输入或绑定一些事件,我就是这么做的。用+1:)感谢我:)我喜欢堆栈溢出:)我们希望您尝试自己解决这个问题,而不是要求社区为您找到一个完整的解决方案。当您有一些代码向我们展示您的一些努力时(即使是错误的),请更新您的问题和标志以重新打开。谢谢
jQuery("#id_of_form").validate({
        rules: {
           "Veggie": {
                required : function(element){
                    return $("input[name='Vegetarian']:checked").val() == "1"
                }
            },
            "NonVeggie": {
                required : function(element){
                    return $("input[name='Vegetarian']:checked").val() == "0"
                }
            }
        }
});