Neethu Kc Neethu Kc - 4 years ago 261
Javascript Question

Javascript function doesn't work on uncheck the check box



$('#checkboxF1').on('change', function() {
alert("test");
});

function check_box() {
document.getElementById("checkboxF1").checked = true;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="check_box" onclick="check_box();">check box</button>
<br>
<br>
<input type="checkbox" id="checkboxF1" class="css-checkbox">Test





The onchange function works when checking the checkbox directly but it doesn't work when checking the checkbox through a function, i.e. the function named
check_box()
.

I want to invoke the onchange function when check the checkbox is check through the function
check_box()
.

Answer Source

Problem is changing the checkbox state does not fires the event. Try trigger instead.

var chk = $('#checkboxF1');

chk.on('change', function() {
  alert("test");
});

function check_box() {
  chk.trigger('click');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<button id="check_box" onclick="check_box();">check box</button>
<br>
<br>
<input type="checkbox" id="checkboxF1" class="css-checkbox">Test

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download