1

I have two arrays. The first array (idContainerArray) contains the ids of the checkboxes I selected across pages.

The second array (idArray) will contain the Ids of the checkboxes of the current page.

I want to compare those two arrays and if a match is found then check the corresponding checkbox on the current page.

The below code execute without errors but won't check the boxes.

jquery :

var idArray = [];
        var idContainerArray = [];

       $.each(idArray, function (i, el) {
            if ($.inArray(el, idContainerArray) != -1) {
                   $(el).prop("checked", true);
            }
        });
BumbleBee
  • 10,429
  • 20
  • 78
  • 123

3 Answers3

3

You're not quite selecting the DOM element correctly. el should be '#' + el:

$("#" + el).prop("checked", true);

Fiddle demo.

Edit

Thanks to @Blender, document.getElementById(el).checked = true seems a less-roundabout way.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
2

You can select the elements in the cross-page list, then filter using the in-page list:

var chkBoxes = $("#" + idContainerArray.join(",#"));
chkBoxes = chkBoxes.filter("#" + idArray.join(",#"));
chkBoxes.prop("checked", true);

You may be able to omit the filter. Is it possible for an element that is contained in idContainerArray to be used as an id on the current page, but not be contained in idArray? Because, if not, you can skip the filter and just do this:

$("#" + idContainerArray.join(",#")).prop("checked", true);

This works even if the id is reused as something other than a checkbox. The checked property won't hurt or have any side effects if it is written to a non-checkbox element. If the id can be reused, but not as a checkbox, and you don't want to write the checked property, you can filter out the non-checkboxes:

$("#" + idContainerArray.join(",#")).filter(":checkbox").prop("checked", true);

Or:

$("#" + idContainerArray.join("[type=checkbox],#") + "[type=checkbox]").prop("checked", true);

This second technique that does not use jQuery's :checkbox shorthand might be a hair faster because it will take advantage of the browser's native querySelectorAll() call. On most pages, you wouldn't notice a difference though.

gilly3
  • 87,962
  • 25
  • 144
  • 176
0

The checked attribute value must be checked. And as McGarnagle pointed out the selector for an id is #

var idArray = [];
    var idContainerArray = [];

   $.each(idArray, function (i, el) {
        if ($.inArray(el, idContainerArray) != -1) {
               $('#' + el).attr("checked", "checked");
        }
    });
Jay
  • 6,224
  • 4
  • 20
  • 23
  • why `attr` and not `prop`? – Sergio Jul 29 '13 at 22:38
  • attr works with the html attributes and prop works with the DOM properties see the [jQuery Documentation](http://api.jquery.com/prop/) for more info. After looking it up, as of jQuery 1.6 `.prop("checked", true)` is the same as `.attr("checked", checked")` – Jay Jul 29 '13 at 22:42