MVC3 Razor - at least one checkbox checked

I am new to mvc3 and razor motor and I would like at least one checkbox to be checked for the submit button to shoot.

<div class="editor-field"> @Html.Label("item1") @Html.CheckBoxFor(Model => Model.item1) @Html.Label("item2") @Html.CheckBoxFor(Model => Model.item2) @Html.Label("item3") @Html.CheckBoxFor(Model => Model.item3) </div> <p> <input type="submit" value="Create" /> </p> 

I know that I will need some kind of shortcut for rendering text if 0 flags are selected, and so that each flag has an identifier, so I can see their values, but is there anything in the mvc3 razor to make this easier? Thanks

+4
source share
2 answers

One way is

 <input type="submit" value="Create" onclick="return submitWith();"/> <span id="validationMessage" /> 

and in your javascript (you may have more here, but simple)

 function submitWith(){ var checkedCount = $("input:checked").length; var valid = checkedCount > 0; if(!valid){ $('#validationMessage').html('You must select at least one option'); } return valid ; } 
+9
source

Check the box with a valid Name attribute. The name of each checkbox must be the same. Say: Name="CheckBoxForItems"

On the Click button, the event of the Create button: (In js)
Declare an array and use each function to check if any checkbox is checked:

 var arr = new Array(); $('input[name="CheckBoxForItems"]:checked').each(function (i) { arr.push($(this).attr("id")); }); if(arr.length > 0) $("#ButtonId").submit(); } 
0
source

Source: https://habr.com/ru/post/1444077/


All Articles