new1.PNG New.PNG new2.PNG new3.PNG Good Day, I would like some assistance, I have 12 checkboxes that when you click the value get stored into the database, then unchecked it get removed. Then now I needed a Checkbox/Uncheck All checkbox that when clicked the values get store, then unclick get removed.

 <b> <span>
                Check/Uncheck All
            </span> <input type="checkbox" id="checkall" /> </b>

<script type="text/javascript">

    function Select(status)

    {

        $("#checkboxes input").each(function ()

        {

            // Set the checked status of each to match the

            // checked status of the check all checkbox:

            $(this).prop("checked", status);

        });

    }

    $(document).ready(function ()

    {

        //Set the default value of the global checkbox to true:

        $("#checkall").prop('unchecked', true);

        // Attach the call to toggleChecked to the

        // click event of the global checkbox:

        $("#checkall").click(function ()

        {

            var status = $("#checkall").prop('checked');

            Select(status);

        });

    });

</script>

You're showing JQuery code. JQuery is client-side (runs via visitor's browser). You're saying you want to store values in a database. That requires server-side code (PHP, ASP, etc.). You can connect the two with AJAX so the page doesn't have to refresh, but you do have to have the server-side code.

Now, with checkboxes, the thing to remember is that a value is returned ONLY when the box is CHECKED. If unchecked, nothing is returned. So it is up to your server-side code to determine if any database fields are set while their POST values have not been sent, in which case you would zero the value in the database.

My Controller for the existing functioning checkboxes. I dont know how to attached my code here. I am new in development world

 public int Assign(string suburb, string[] subcouncils, int recyclerId)
        {
            using (var db = new WasteRecyclersEntities())
            {
                int result = 0;

                var query = db.Locations.Where(l => l.RecyclerId == recyclerId && l.Suburb == suburb).FirstOrDefault();

                if (query == null)
                {
                    foreach (var subcouncil in subcouncils)
                    {
                        var loc = new Location
                        {
                            DateAdded = DateTime.Now,
                            Type = Location.CollectionAreaType(),
                            Suburb = suburb,
                            Subcouncil = subcouncil,
                            RecyclerId = recyclerId
                        };

                        db.Locations.Add(loc);
                    }

                    result = db.SaveChanges();
                }

                return result;
            }
        }
        public int Remove(string suburb, int recyclerId)
        {
            using (var db = new WasteRecyclersEntities())
            {
                int result = 0;

                var query = db.Locations.Where(l => l.RecyclerId == recyclerId && l.Suburb == suburb).ToList();

                if (query != null)
                {
                    foreach (var loc in query)
                    {
                        db.Locations.Remove(loc);
                    }

                    result = db.SaveChanges();
                }

                return result;
            }
        }

My ViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CityOfCapeTown.WasteRecyclers.Intranet.ViewModels
{
    public class ManageCollectionAreasViewModel
    {
        public int Id { get; set; }

        public List<SelectListItem> CollectionAreas { get; set; }
        public string AddressLayerUrl { get; set; }
        public string MainSuburbsLayerUrl { get; set; }

        public ManageCollectionAreasViewModel()
        {
            CollectionAreas = new List<SelectListItem>();
        }

        public string SubcouncilsLayerUrl { get; set; }

        public string EsriArcgisApi { get; set; }
    }
}

My Javascript

function listMajorSuburbs(mainSuburbsLayerUrl, subcouncilsLayerUrl) {
    require(["esri/tasks/query", "esri/tasks/QueryTask"],
               function (Query, QueryTask) {
                   var q = new Query();

                   fields =["SBRB_NAME"];
                   q.outFields = fields;
                   q.orderByFields = fields;
                   q.where = 'SBRB_NAME IS NOT NULL';

                   var suburbsDiv = $('#suburbsDiv')

                   var qt = new QueryTask(mainSuburbsLayerUrl);
                   qt.execute(q, function (data) {
                       $.map(data.features, function (suburb) {

                           var chk = '<label>'
                               + '<input type="checkbox" name="collectionAreas" onClick="getSubcouncils(this)" value="' + suburb.attributes['SBRB_NAME']+ '" /> ' + suburb.attributes['SBRB_NAME']
                               + ' <span></span>'
                               + ' </label><br/>';

                           suburbsDiv.append(chk)
                       });

                       highlightSelectedCollectionAreas(recyclerId)
                       }, function (error) {
                       console.log('error', error)
                       alert(error)
                   });
                   });

                   function highlightSelectedCollectionAreas(recyclerId) {
                       $.ajax({
                           url: getUrl("GetCollectionAreas", "CollectionArea"),
                type: "GET",
                    data: {
                       recyclerId: recyclerId
                   },
                           dataType: "json",
                               success: function (data) {
                                   for (var i = 0; i < data.length; i++) {
                                       $('input[value="' +data[i]+ '"]').attr('checked', true);
                }
            },
                error : function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(JSON.stringify(XMLHttpRequest))
                    alert("An error occured assiging collection areas");
            }
            });
            }
            };
            function getSubcouncils(input) {
                require(["esri/tasks/query", "esri/tasks/QueryTask"],
                    function (Query, QueryTask) {

                        if (input.checked) {
                var q = new Query();
                q.returnGeometry = true;

                fields =["SBRB_NAME"];
                q.outFields = fields;
                q.orderByFields = fields;
                var inputValue = input.value.replace(/'/g, "''");
                q.where = "SBRB_NAME = '" +inputValue + "'";

                var qt = new QueryTask(mainSuburbsLayerUrl);
                qt.execute(q, function (data) {
                    $.map(data.features, function (suburb) {
                        var q = new Query();

                        fields =["SUB_CNCL_NAME"];
                        q.outFields = fields;
                        q.geometry = suburb.geometry;
                        q.spatialRelationship = Query.SPATIAL_REL_INTERSECTS;

                        var qt = new QueryTask(subcouncilsLayerUrl);
                        qt.execute(q, function (data) {
                            subcouncils =[];

                            $.map(data.features, function (sc) {
                                subcouncils.push(sc.attributes['SUB_CNCL_NAME']);
                            });

                            assignCollectionAreas(recyclerId, input.value, subcouncils)

                        }, function(error) {
                            console.log('error', error)
                            alert(error)
                        });
                    });
                    });
                    }
                    else {
                removeCollectionAreas(recyclerId, input.value)
                    }
                    });

    function removeCollectionAreas(recyclerId, suburb) {
                    var lblMessage = $('#lblMessage')
        $.ajax({
                            url: getUrl("Remove", "CollectionArea"),
                            type: "POST",
                        traditional: true,
                data: {
                    recyclerId: recyclerId,
                    suburb: suburb
                    },
                    dataType: "json",
                            success: function (data) {
                        if (data == 0) {
                    alert('No Collection Areas were removed')
                }
                    else {
                    lblMessage.text(suburb + ' Collection Area removed succesfully.');
                }
                },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log(JSON.stringify(XMLHttpRequest))
                alert("An error occured assiging collection areas");
                        }
                        });
                }
            function assignCollectionAreas(recyclerId, suburb, subcouncils) {
                var lblMessage = $('#lblMessage')
                $.ajax({
                url: getUrl("Assign", "CollectionArea"),
                    type: "POST",
                        traditional: true,
                    data: {
                    recyclerId: recyclerId,
                    suburb: suburb,
                    subcouncils: subcouncils
            },
                dataType: "json",
                        success: function (data) {
                if (data == 0) {
                    alert('No Collection Areas were assigned')
                }
                    else {
                    lblMessage.text(suburb + ' Collection Area assigned succesfully.')
                    }
                    },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log(JSON.stringify(XMLHttpRequest))
                alert("An error occured assiging collection areas");
                    }
                    });
                    }
                    }

My View

<fieldset>
    <legend>
        Assign Major Suburbs
    </legend>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.Id)

        <div id="checkboxes" style="height: 500px;position:relative;border:1px solid darkgray">
            <div id="div2" style="max-height:100%;overflow:auto;">
                <b>
                <span>
                    Check/Uncheck All
                </span>
                <input type="checkbox" id="checkall" />
                </b>
                <br />
                <br />
                <div id="suburbsDiv"></div>
            </div>
        </div>
        <br />
        <div id="lblMessage"></div>

        <br />
        <a href="@Url.Action("ManageServices", "Recycler", new { id = Model.Id })" class="backButtonLink">
            Back
        </a>
        <input id="btnSubmit" type="submit" value="Next" />
    }
</fieldset>

@section Scripts
    {
    @Scripts.Render("~/bundles/jqueryval")
    <script src="@Model.EsriArcgisApi"></script>

    <script src="~/Scripts/wasterecyclersGIS.js"></script>

    <script>
        $(document).ready(function () {
            recyclerId = '@Model.Id';
            mainSuburbsLayerUrl = "@Model.MainSuburbsLayerUrl";
            subcouncilsLayerUrl = "@Model.SubcouncilsLayerUrl";
            listMajorSuburbs(mainSuburbsLayerUrl, subcouncilsLayerUrl);
        });
    </script>
    <script type="text/javascript">
        function Select(status)
        {
            $("#checkboxes input").each(function ()
            {
                // Set the checked status of each to match the
                // checked status of the check all checkbox:
                $(this).prop("checked", status);
            });
        }
        $(document).ready(function ()
        {
            //Set the default value of the global checkbox to true:
            $("#checkall").prop('unchecked', true);
            // Attach the call to toggleChecked to the
            // click event of the global checkbox:
            $("#checkall").click(function ()
            {
                var status = $("#checkall").prop('checked');
                Select(status);
            });
        });
    </script>

}

my current checkboxlist works just fine, then had to come with check-all checkbox which is checking and unchecking all checkboxes, but on check the database is not updated

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.