Reputation: 201
I got a check box on the html page as:
<input type="checkbox" id="chk-info" name="chk-info" />
when I try to write an on change event and run, it's not getting fired. Instead if, I place an alert message before the function it is firing fine.
alert('blah');
var sth = function(){
function m(){
$("input[type='checkbox']").click(function (e) {
if ($(this).is(':checked')) {
alert("true");
} else {
alert("false");
}
});
}
return{ m:m};
};
I have tried using the id selector as well, but with not much luck. Can anyone help me in pointing where the issue is?
EDIT: When I place the check box checked function outside the above function it works well with 'onchange' event attached on the <input>
tag
Upvotes: 2
Views: 12126
Reputation: 1
$(document).ready(function () {
$("input[type='checkbox']").click(function (e) {
if ($(this).is(':checked')) {
$(this).val("true");
} else {
$(this).val("false");
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="checkbox" id="chk-info" name="chk-info" />
<label for="chk-info">label</label>
Upvotes: 0
Reputation: 4590
Put the onclick event of the checkbox on page load.
$(document).ready(function () {
$("input[type='checkbox']").click(function (e) {
if ($(this).is(':checked')) {
alert("true");
} else {
alert("false");
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="checkbox" id="chk-info" name="chk-info" />
<label for="chk-info">label</label>
Upvotes: 5