Sumon Bappi Sumon Bappi - 2 months ago 7
Javascript Question

Why Checkbox is not unchecking in jquery

I need to uncheck a checkbox. It is doing everything like alert or removing div, but not unchecking the checkbox. I have used both

attr
and
prop
methods. The checkbox
id
is ok. Even it doesn't show any error in firebug console.

$('html').on('click', '#inScopeDiv .remButton', function () {
var currId = $(this).attr('id');
var chkBoxId = "#chk"+currId;
alert(currId);
alert('#chk'+currId);
$(chkBoxId).prop("checked", false);
$(chkBoxId).attr("checked", false);
$('#div'+ currId).remove();
$('#inScopeActionDiv' + currId).remove();
});


HTML provided ::

<c:forEach items="${data.inScope}" var="inScopeValues">
<div class="col-md-12" style="background-color: snow;">
<input class="inScope" type="checkbox" id="chk${inScopeValues.key}" name="chk + ${inScopeValues.key}" value="${inScopeValues.value}">
${inScopeValues.value}
</div>
</c:forEach>


Button & Checkbox is below ::>

<input class="inScope" type="checkbox" id="chkisc_2" name="chkisc_2" value="In Scope 2">

<button id="chkisc_1" type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>

Answer

The button you show in the updated question has id="chkisc_1", then in your function you take that and add #chk to the beginning of it which would mean you're looking for an element with the selector "#chkchkisc_1". Meanwhile, apparently the checkbox has id="chkisc_2", although it does seem to be created in a loop so perhaps there is also a _1 (though that would mean you have more than one element with the same id, which is invalid html).

Change the button to have id="isc_1", then when your JS adds #chk it will be looking for #chkisc_1:

$('html').on('click', '#inScopeDiv .remButton', function () {
    var currId = $(this).attr('id');
    var chkBoxId = "#chk"+currId;
    $(chkBoxId).prop("checked", false);
    $('#div'+ currId).remove();
    $('#inScopeActionDiv' + currId).remove();         
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="inScopeDiv">

<input class="inScope" type="checkbox" id="chkisc_1" name="chkisc_1" value="In Scope 1" checked>
<button id="isc_1" type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>

<input class="inScope" type="checkbox" id="chkisc_2" name="chkisc_2" value="In Scope 2" checked>
<button id="isc_2" type="button" class="btn btn-warning btn-sm remButton" title="Remove this item">Remove Item</button>
</div>