Sadikhasan Sadikhasan - 4 months ago 11
Javascript Question

Checkbox with ajax issue for select or unselect issue

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.

Answer

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;
});
Comments