2015-12-08 102 views
0

我在我的asp.net mvc剃刀視圖中生成一個複選框列表中的以下部分。 我希望能夠驗證至少有一個被打勾。檢查至少一個複選框檢查jquery驗證

<div class="form-group"> 
    <div class="row col-md-12 "> 
    <div class=" col-md-11 col-md-offset-1"> 
     @for (int i = 0; i < Model.PeronsExpList.Count(); i++) 
     { 
     <div class="col-md-12"> 
      @Html.HiddenFor(x => Model.PeronsExpList[i].PeronExpId) 
      @Html.CheckBoxFor(x => Model.PeronsExpList[i].selected, new { @class = "{peopleExp: true}", @name = "peopleExp"}) 
      @Html.DisplayFor(x => Model.PeronsExpList[i].PeronName, Model.PeronsExpList[i].PeronName) 
     </div> 
     } 
    </div> 
    </div> 
</div> 

我有以下的JavaScript來提供此功能:

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
    <script type="text/javascript"> 

    $.validator.addMethod("peopleExp", function (value, elem, param) { 
    if ($(".peopleExp:checkbox:checked").length > 0) { 
     return true; 
    } else { 
     return false; 
    } 
    }, "You must select at least one!"); 

    </script> 
} 

然而,當我測試它,它讓我提交即使沒有被選中TE頁。

+1

http:// js fiddle.net/chriscoyier/bphze/76/ – Jinandra

+0

該鏈接僅僅是IE和Chrome瀏覽器頁面上對象的混亂 –

+0

您可能需要重新加載頁面。在兩端瀏覽器上都能正常工作。 – Jinandra

回答

0

感謝@AmitSingh用於鏈接的資源來解決這個

查看修改爲:

 <div class="form-group"> 
     <div class="row col-md-12 "> 
      <div class=" col-md-11 col-md-offset-1"> 
       @for (int i = 0; i < Model.PeronsExpList.Count(); i++) 
       { 
        <div class="col-md-12"> 
         @Html.HiddenFor(x => Model.PeronsExpList[i].PeronExpId) 
         @Html.CheckBoxFor(x => Model.PeronsExpList[i].selected, new { @type = "checkbox"}) 
         @Html.DisplayFor(x => Model.PeronsExpList[i].PeronName, Model.PeronsExpList[i].PeronName) 
        </div> 
       } 
      </div> 
     </div> 
    </div> 

薩米特按鈕改爲:

<input type="submit" name="Submit" value="Add Control Measure" class="btn btn-primary" disabled /> 

的Javascript修改爲:

@section Scripts { 
@Scripts.Render("~/bundles/jqueryval") 
<script type="text/javascript"> 

    var checkboxes = $("input[type='checkbox']"), 
     submitButt = $("input[type='submit']"); 

    checkboxes.click(function() { 
     submitButt.attr("disabled", !checkboxes.is(":checked")); 
    }) 
</script> 
} 
相關問題