仅当选中此单选按钮时,复选框验证

时间:2015-05-12 18:45:52

标签: jquery html asp.net asp.net-mvc validation

我正在尝试验证下面的单选按钮是否为真,那么必须至少选中一个复选框。

     @using (Html.BeginForm("Print","Home",FormMethod.Post, new{ @class="form", role ="form")
     {
    @Html.AntiForgeryToken();
    <div class="col-md-12">
        <div class="alert alert-info">
            If you are multiracial, please complete this item by indicating the ethnic/racial group you identify with most or the ethnic/racial group to which you are usually regarded in the community as belonging.
        </div>
    </div>
    <div class="col-md-9">
        <div class="form-group">
            @Html.LabelFor(model => model.IsMultiracial, "Are you Multiracial?", new { @class = "control-label" })
            @Html.RadioButtonFor(model => model.IsMultiracial, "false", new { onclick = "showRacial(this.value)" }) No
            @Html.RadioButtonFor(model => model.IsMultiracial, "true", new { onclick = "showRacial(this.value)" }) Yes
        </div>
    </div>
</div>
<div class="row">
    <div id="multiracial" style="display: none;">
        <div class="col-md-9">
            <div class="form-group">
                @for (int i = 0; i < Model.ParentRacialGroups.Count(); i++)
                {
                    <input type="hidden" name="ParentRacialGroups.Index" value="@i" />
                    <input type="checkbox" id="ParentRacialGroup" name="ParentRacialGroups[@i].ID" value="@Model.ParentRacialGroups[i].ID" checked="@Model.ParentRacialGroups[i].isChecked" data-size="xs" />
                    <label class="cbx-label small" for="check-2g">@Model.ParentRacialGroups[i].name</label>
                    <br />
                }

            </div>
        </div>
    </div>
</div>
<hr>
<div class="row">
    <div class="col-md-offset-2 col-md-4">
        <div class="form-group">
            <input type="submit" class="btn btn-default" value="Print" />
        </div>
    </div>
</div>
  }

1 个答案:

答案 0 :(得分:0)

我不知道这对您是否有用,但您仍然可以尝试使用此逻辑来使用JavaScript进行工作

JSFiddle : Demo

<强> HTML

1 <input type="checkbox" value="1" name="chk" />
2 <input type="checkbox" value="2" name="chk" />
3 <input type="checkbox" value="3" name="chk" />
<br><br>
Radio <input type="radio" value="1" />

<强> JS

var radio = $("input[type='radio']");

radio.click(function() {
var $boxes = $('input[name=chk]:checked');
var num = $boxes.length;

 if(num>0)
 {
    alert(num + " " + "Checkbox selected");
 }
 else
 {
     alert("Not a single Checkbox selected");
 }

});