October 23, 2024
Chicago 12, Melborne City, USA
jQuery

Selecting Checkbox values based on JSON Array


I am storing some id values as json strings in my database. I am using these same ids as the checkbox values in my Bootstrap multiselect checkbox control on my form.

[{"formLookupId":16},{"formLookupId":23},{"formLookupId":17}]

My approach is to set a hiddenField value with this array, and then use JS to set the checkbox selected values appropriately (since I cannot do this on the server-side as they are not server controls).

 <asp:HiddenField ID="hdnFormchkboxes" runat="server" ClientIDMode="Static" />

I am close with this approach, but I am not sure what I am missing here in terms of the javascript. Can someone help me understand what I am doing wrong? I don’t have a lot of experience with json arrays in JS and my JS code is not passing the values.includes(parseInt(checkbox.value)) test. Also, if there is a better way to do this that is more efficient that doesn’t involve making my controls server-side controls,but allows me to manipulate these checkboxes server-side, I am open to that.

HTML sample checkbox control:

<label class="checkbox"><input type="checkbox" value="16"> FooBar Checkbox </label>

JS:

 if ($('#hdnFormchkboxes').attr('value') != null && $('#hdnFormchkboxes').attr('value') != '') {
            var hdnFormcheckedvals = $('#hdnFormchkboxes').attr('value');
            var values = JSON.parse(hdnFormcheckedvals);

            var container = document.querySelector('.ddlchkProfessionCheckboxes');
            const checkboxes = container.querySelectorAll('input[type="checkbox"]');               

            checkboxes.forEach(checkbox => {
                if (values.includes(parseInt(checkbox.value))) {
                    checkbox.checked = true;
                }
            });
        }



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video