简体   繁体   中英

Javascript - Check checkbox if Multiple Checkboxes selected

I was wondering if someone could help me with some javascript as I'm quite unfamilar with it and unfortunately have been tasked with writing a function for tomorrow, and I appear to be failing miserably.

In my MVC application, I have a View where the user can select multiple outlets within a particular groupHeader. Already written was SelectAll, and DeselectAll javascript functions to select all (or deselect all) outlets within a groupHeader, however I am unsure how to use these functions within other functions.

I need to limit the existing functionality which will only allow the user to select the groupHeader, and this should select all the outlets within that group. Unfortunately this part of the application affects other parts so the underlying functionality must remain the same.

What I would ideally like is to have javascript to do the following:

If the groupHeader checkbox is checked, call the selectAll function. If the groupHeader checkbox is unchecked, call the deselectAll function.

As the selections need to be remembered, which would be figured out from the controller, it would also be necessary to have the following functions:

On page load, if all outlets are checked in particular section, check the groupHeader checkbox. On page load, if all outlets are unchecked in particular section, uncheck the groupHeader checkbox.

Here is the view:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <script src="/Scripts/FormHelpers.js" type="text/javascript"></script>

    <script type="text/javascript">
        function selectAll(sectionId) {
            toggle(sectionId, "checked");
        }

        function deselectAll(sectionId) {
            toggle(sectionId, null);
        }

        function toggle(sectionId, checked) {
            $('[section$=' + sectionId + ']').each(function () { $(this).attr('checked', checked); });
        }

    </script>
    <div>
        <% int i = 0; %>
        <% Html.BeginForm(); %>
        <% { %>
        <% foreach (App.Web.Models.OutletGroup g in Model.Groups) %>
        <% { %>
        <div style="width:700px;">
            <div style="border-bottom: 1px solid;">
                <div style="font-weight: bold; font-size: larger; width: 300px; float: left;">
                   <input type="checkbox" id="GrpHdr" /> <%: g.GroupHeader%>
                </div>
                <div style="line-height: 18px; vertical-align: middle; width: 250px; float: left;">
                    <a id="select" href="javascript:selectAll(<%: i %>)" <%: ViewData["GROUP_ALL_SELECTED_" + g.GroupHeader] %>>
                        Select All</a> / <a id="deselect" href="javascript:deselectAll(<%: i %>)" <%: ViewData["GROUP_ALL_SELECTED_" + g.GroupHeader] %>>
                            Deselect All</a>
                </div>
                <div style="clear: both;">
                </div>
            </div>
        </div>
        <div style="margin-left: 10px; margin-top: 10px;">
            <% foreach (App.Data.Outlet outlet in g.Outlets) %>
            <% { %>
            <div style="float: left; line-height: 18px; padding: 2px; margin: 2px; vertical-align: middle;
                border: 1px solid grey; width: 282px;">
                <input type="checkbox" section="<%: i %>" name="OUTLET_<%: outlet.OutletID %>" <%: ViewData["OUTLET_" + outlet.OutletID] %>
                    style="vertical-align: middle; padding-left: 5px;" />
                <%= Html.TrimTextToLength(outlet.Name)%>
            </div>
            <% } %>
        </div>
        <div style="clear: both; margin-bottom: 5px;">
            &nbsp;</div>
        <% i++; %>
        <% } %>
        <br />
        <br />
        <div class="buttonFooter">
            <input type="submit" value="Update" />
        </div>
        <div style="clear: both;">
        </div>
        <% } %>
    </div>
</asp:Content>

Here is the controller code also:

public class OutletsController : Controller
    {
        public ActionResult Index()
        {
            // Get all the outets and group them up.
            //
            ModelContainer ctn = new ModelContainer();
            var groups = ctn.Outlets.GroupBy(o => o.Header);

            OutletViewModel model = new OutletViewModel();

            foreach (var group in groups)
            {
                OutletGroup oGroup = new OutletGroup()
                {
                    GroupHeader = group.Key,
                };

                model.Groups.Add(oGroup);
            }

            foreach (var group in model.Groups)
            {
                group.Outlets = ctn.Outlets.Where(o => o.Header == group.GroupHeader).ToList();
            }

            // Get the existing details and check the necessary boxes (only read undeleted mappings).
            //
            var currentOutlets = ctn.UserOutlets.Where(uo => uo.UserID == UserServices.CurrentUserId && !uo.Deleted);

            foreach (var outlet in currentOutlets)
            {
                ViewData["OUTLET_" + outlet.OutletID] = "checked='checked'";
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(FormCollection formValues)
        {
            // Update the existing settings.
            //
            ModelContainer ctn = new ModelContainer();
            var outlets = ctn.UserOutlets.Where(uo => uo.UserID == UserServices.CurrentUserId);

            foreach (var outlet in outlets)
            {
                outlet.Deleted = true;
                outlet.UpdatedDate = DateTime.Now;
                outlet.UpdatedBy = UserServices.CurrentUserId;
            }

            // Save all the selected Outlets.
            //
            foreach (string o in formValues.Keys)
            {
                if (o.StartsWith("OUTLET_"))
                {
                    UserOutlet uo = new UserOutlet();
                    uo.UserID = UserServices.CurrentUserId;
                    uo.OutletID = int.Parse(o.Substring("OUTLET_".Length));
                    uo.CreatedDate = DateTime.Now;
                    uo.CreatedBy = UserServices.CurrentUserId;
                    ctn.UserOutlets.AddObject(uo);
                }
            }

            ctn.SaveChanges();

            return RedirectToAction("Index");
        }
    }

I'd be very grateful if anyone could offer some help, or point me in the right direction.

Thanks!

EDIT:

Edited the javascript to include the following as suggested by Tejs:

$('.GrpHdr').each(function()
 {
     var elements = $(this).find('input[name|="OUTLET_"]');


        var checkboxCount = elements.filter(':checked').length;

        if (checkboxCount == elements.length)
            $('.GrpHdr').attr('checked', this.checked);
        else if (checkboxCount == 0)
            $('.GrpHdr').attr('checked', !this.checked);
    });

However I can't seem to get this to work for me. Can anyone see what's going wrong?

First, you need to change the GrpHdr checkbox to use a class or something; currently, it looks like you generate multiple checkboxes with the same Id which is never good. Assuming you change it to a class like so:

  <input type="checkbox" class="GrpHdr" />

Then you can write something like this to check the checked status:

 $('.GrpHdr').each(function()
 {
     var elements = $(this).find('input[name|="OUTPUT_"]');

     var checkboxCount = elements.filter(':checked').length;

     if(checkboxCount == elements.length)
        // All Checked, Do Some Logic
     else if(checkboxCount == 0)
        // None checked, do some logic
     else
        // Some Checked and some not checked
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM