0

I have written the following function to check checkboxes based on a set of feature filters, which is an array returned by a separate function.

$(function() {
    $('#device_form').find(':checkbox[name^="feature_filters"]').each(function () {
      $(this).prop("checked", (jQuery.inArray($(this).attr('data-feature-id'), feature_filters) != -1 ));
      console.log("feature_filters " + jQuery.type(feature_filters) + " " + feature_filters);
      console.log("data-feature-id " + $(this).attr('data-feature-id'));
      console.log("In Array Result " + jQuery.inArray($(this).attr('data-feature-id'), feature_filters));
    });
});

The log is interesting:

feature_filters array 2,10
data-feature-id 9
-> inArray Result -1

feature_filters array 2,10
data-feature-id 2
-> inArray Result -1

As you can see the inArray result should be 0 for the last example. What am I doing wrong?

Community
  • 1
  • 1
Abram
  • 39,950
  • 26
  • 134
  • 184

1 Answers1

0

As suggested by @adeneo, I needed to convert data-feature-id to integer format in order for inArray to work properly. Here is my answer:

  $(function() {
    $('#device_form').find(':checkbox[name^="feature_filters"]').each(function () {
      num = parseInt($(this).attr('data-feature-id'), 10);
      $(this).prop("checked", (jQuery.inArray(num, feature_filters) != -1 ));
    });
  });
Abram
  • 39,950
  • 26
  • 134
  • 184