MVC4 Jquery验证复选框至少检查一个?

时间:2015-07-28 02:18:32

标签: javascript jquery asp.net-mvc-4 checkbox requiredfieldvalidator

我实施了一个复选框问题,让用户可以选择。但是,如果admin将问题强制设置为true,则复选框必须至少选择1才能提交,否则将显示一条消息,提示用户选择。尝试了jquery但是当点击按钮时,没有任何事情发生。

我做过的任何错误?

我的观点:

    @model List<IFXSurveyTool.Models.AnswerQuestionViewModel>

    <script>

            var messageContainer = $('.errormessage');

            $('#save').click(function () {
                // Get all mandatory containers
                var mandatory = $('.mandatory');
                $.each(mandatory, function () {
                    var numChecked = $(this).find('input:checked').length;
                    if (numChecked === 0) {
                        messageContainer.text('At least one checkbox must be selected.');
                        return false;
                    }
                });
            });

            $('.mandatory').on('click', 'input[type="checkbox"]', function () {
                messageContainer.text('');
            });


    </script>

    <br />
    <h2>Questions</h2>
    <br />

    @using (Html.BeginForm())
    {
        <div class="errormessage"></div>
           <div class="checkboxcontainer mandatory">
              @for (int x = 0; x < Model[i].Choice_SubQuestion.Count(); x++)
                  {


                           <input type="checkbox" name="[@i].MultiAnswer[@x]" value="@Model[i].Choice_SubQuestion[x]" />
                           @Html.HiddenFor(m => m[i].MultiAnswer[x])
                           @Html.LabelFor(m => m[i].MultiAnswer[x], Model[i].Choice_SubQuestion[x].ToString(), new { @class = "questionlist1" })



         }
  </div>

    <button type="button" id="save">Save</button> 
}

在HTML中生成复选框后:

<div class="checkboxcontainer mandatory">
<input type="checkbox" name="[0].MultiAnswer[0]" value="1">
<input name="[0].MultiAnswer[0]" type="hidden" value="">
<label class="questionlist1" for="">1</label>
<input type="checkbox" name="[0].MultiAnswer[1]" value="2">
<input name="[0].MultiAnswer[1]" type="hidden" value="">
<label class="questionlist1" for="">2</label>
<input type="checkbox" name="[0].MultiAnswer[2]" value="3">
<input name="[0].MultiAnswer[2]" type="hidden" value="">
<label class="questionlist1" for="">3</label>
</div>

1 个答案:

答案 0 :(得分:1)

首先,您提供所有包含<div>元素的class="mandatory"元素,并且只有在Model[i].Mandatorytrue时才生成复选框,因此您应该

for (int x = 0; x < Model[i].Choice_SubQuestion.Count; x++)
{
  @{var attributes = Model[i].Mandatory ? "checkboxgroup mandatory" : "checkboxgroup";}
  <div class="@attributes">
    <div class="message></div>
    <input type="checkbox" name="[@i].MultiAnswer[@x]" value="@Model[i].Choice_SubQuestion[x]" />
    @Html.HiddenFor(m => m[i].MultiAnswer[x])
    @Html.LabelFor(m => m[i].MultiAnswer[x], Model[i].Choice_SubQuestion[x].ToString(), new { @class = "questionlist1" })
  </div>
}
<input value="Submit" type="submit" class="btn" id="save" />

接下来,您的按钮是一个提交按钮,因此表单实际上是在提交之前(错误消息有可能变为可见)。将脚本更改为

$('#save').click(function() {
  var canSubmit = true;
  // Get all mandatory containers
  var mandatory = $('.mandatory');
  $.each(mandatory, function() {
    var numChecked = $(this).find('input:checked').length;
    if (numChecked === 0) {
      canSubmit = false; // signal we can't submit
      // display error message;
      $(this).children('.message').text('At least one checkbox must be selected');

      return false; // exit the loop
    }
  });
  if (!canSubmit) {
    return false; // cancel the default submit
  }
});

$('.mandatory').on('click', 'input[type="checkbox"]', function() {
  $(this).closest('.mandatory').children('.message').text(''); // clear any existing error message
});

另请注意,脚本必须位于页面底部(紧接结束</body>标记之前)或包含在$(document).ready() { ..... }$(function() { ..... });(速记版本)中。