0

I have the following code to retrieve ids from permissions with AJAX

$('#verPermisos').click(function() {                
    var role = $('#roles :selected').val();

    $.ajax({
        type: "POST",
        url: "populate",
        data: { role : role },
        success: function(data) {
            console.log(data);
            var permisoArreglo = data;
            $.each(permisoArreglo, function(index, value) {
                $("input:checkbox[value=" + permisoArreglo[index] + "]").attr("checked", true);
            });
        }
    });

However I also need it to reset the checkboxes every time its clicked Ive tried

$(this).closest('form').find("input[type=checkbox]").attr('checked', false);
$('input[type=checkbox]').attr('checked', false);

I dont have any problem unchecking boxes invidually but when I use

$('input[type=checkbox]').attr('checked', false);

it no longers checks any boxes

However it hasn't worked.

Mntfr
  • 483
  • 6
  • 20
  • 5
    Try `prop('checked', false)`. Failing that, make sure that the AJAX request is hitting the `success` handler, and that the DOM traversal you're using is actually finding the element you expect it to – Rory McCrossan Nov 04 '16 at 16:02
  • Possible duplicate of [check / uncheck checkbox using jquery?](http://stackoverflow.com/questions/17420534/check-uncheck-checkbox-using-jquery) – Captain Squirrel Nov 04 '16 at 16:04
  • It worked changing both to .prop thank you very much – Mntfr Nov 04 '16 at 16:19

2 Answers2

0

This should work

Javascript

$('input[type="checkbox"]').prop('checked', false);

JSFiddle

Sofiene Djebali
  • 4,398
  • 1
  • 21
  • 27
0

Either .attr('checked', false) or .prop('checked', false) should work (at least with the latest version of jQuery. If neither of those work, the problem might be something else, such as something re-resetting it after it's reset triggers, or you might have just had a simple typo or never got to the portion of code you were trying it in.

$(() => {
  $('#withAttr').click(() => { $('input[type="checkbox"]').attr('checked', false); });
  $('#withProp').click(() => { $('input[type="checkbox"]').prop('checked', false); });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><input type="checkbox" checked> Checkbox</p>
<button id="withAttr">Clear with Attr</button>
<button id="withProp">Clear with Prop</button>
samanime
  • 25,408
  • 15
  • 90
  • 139