c# - Jquery check all dynamic checkboxlist in MVC view -
recently created dynamic checkboxlist , display them in c# mvc razor view.
<ul> @for (int = 0; < model.sites.count; i++) { <li> @html.checkboxfor(m => m.sites[i].ischeck) @html.labelfor(m => m.sites[i].ischeck, model.sites[i].sitename) @html.hiddenfor(m => m.sites[i].siteid) @html.hiddenfor(m => m.sites[i].sitename) </li> (int j = 0; j < model.sites[i].roomz.count; j++) { @html.checkboxfor(m => m.sites[i].roomz[j].ischeck) @html.labelfor(m => m.sites[i].roomz[j].ischeck, model.sites[i].roomz[j].roomname) @html.hiddenfor(m => m.sites[i].roomz[j].roomid) @html.hiddenfor(m => m.sites[i].roomz[j].roomname) } } </ul>
below image display of checkboxes
how use jquery on check sites.ischeck check sub-item under same sites? example check co2 check suite 1&2
modify html can use relative selector including adding class names checkboxes.
<ul> @for (int = 0; < model.sites.count; i++) { <li> @html.checkboxfor(m => m.sites[i].ischeck, new { class = "parent" }) @html.labelfor(m => m.sites[i].ischeck, model.sites[i].sitename) @html.hiddenfor(m => m.sites[i].siteid) @html.hiddenfor(m => m.sites[i].sitename) <div> // suggest style give margin-left indented relative parent (int j = 0; j < model.sites[i].roomz.count; j++) { @html.checkboxfor(m => m.sites[i].roomz[j].ischeck, new { class = "child" }) @html.labelfor(m => m.sites[i].roomz[j].ischeck, model.sites[i].roomz[j].roomname) @html.hiddenfor(m => m.sites[i].roomz[j].roomid) @html.hiddenfor(m => m.sites[i].roomz[j].roomname) } <div> </li> } </ul>
then can handle .change()
event of 'parent' checkbox , 'child' checkboxes within same <li>
element
$('.parent').click(function() { var ischecked = $(this).is(':checked'); var children = $(this).closest('li').find('.child'); $.each(children, function(index, item) { $(this).prop('checked', ischecked); }); });
you want handle the child checkboxes well, if uncheck child, parent unchecked, or if check child, , children checked, the parent checked.
$('.child').click(function () { var parent = $(this).closest('li').find('.parent'); var ischecked = $(this).is(':checked'); if (!ischecked) { // parent must unchecked parent.prop('checked', false); } else { // check if siblings have same checked status var siblings = $(this).siblings('.child'); var total = siblings.length; var matches = siblings.filter(function () { return $(this).prop('checked') == ischecked; }).length; if (matches === total) { parent.prop('checked', ischecked); } } })
Comments
Post a Comment