-2

I have checkbox code in html below format

<label class="checkbox-inline">
  <input type="checkbox" name="category[]" value="1" data-id="1" class="categorychk" checked="checked">Men                    
</label>
<label class="checkbox-inline">
  <input type="checkbox" name="category[]" value="2" data-id="2" class="categorychk" checked="checked">Women                    
</label>

On ajax success response I doing following jquery code it will work fine.

$.each(data, function(index,value) {
      $(".categorychk[data-id="+value+"]").attr("checked",true);
});

But issue is before call I clear all checked marks and then apply above code. But it does not work.

When I add following code after ajax call

$(".categorychk").each(function(){
     $(this).removeAttr("checked");
});

Note : If apply above code without clear checked marks then working fine with the previous checked checkbox.

Sadikhasan
  • 17,858
  • 20
  • 77
  • 117

2 Answers2

1

As documented in how do i check uncheck a checkbox input or radio button you need to use jQuery prop:

$(".categorychk[data-id="+value+"]").prop('checked', true);

And to filter elements by data-id you can use:

$(".categorychk").filter(function() {
      return $(this).data('id') == value;
});
gaetanoM
  • 40,728
  • 6
  • 37
  • 54
1

Ok. You're trying to do stuff with attributes, when you should be using properties. Read http://api.jquery.com/attr/, specifically the section entitled "attributes vs properties".

In the meantime, your code will work if you change

$(".categorychk").each(function(){
 $(this).removeAttr("checked");
});

to

$(".categorychk").prop("checked", false);

(N.B. you don't need to .each() this, it will operate on all the selected items automatically).

and change

$(".categorychk[data-id="+value+"]").attr("checked",true);

to

$(".categorychk[data-id="+value+"]").prop("checked",true);

Note the use of .prop() instead of .attr()

ADyson
  • 51,527
  • 13
  • 48
  • 61