Get if checkbox is checked or not in jquery/ES6
Following is my jQuery code by which I am trying to retrieve whether the checkbox is clicked or not. I used both is
and prop
but somehow its always returning false
and undefined
in console. Let me know what I am doing wrong here.
Also, let me know the more better way to handle the checkbox value is to target the click
or change
event on checkbox( currently I am listening to click
event).
jQuery Code -
const $document = $(document);
$document.ready(() => {
$("input[type='checkbox']").on('click', () => {
console.log("Checked Value 'is' :: ", $(this).is(':checked'));
console.log("Checked Value 'prop' :: ", $(this).prop('checked'));
})
})
HTML CODE -
<form name="myForm" id="#myForm">
<div>
<p><input type="checkbox" name="accept-t-and-c" /> I accept terms and conditions</p>
</div>
<div>
<button type="submit" name="submit">Submit</button>
</div>
</form>
JSFIDDLE - https://jsfiddle.net/82Lz1c8w/4/
EDIT - Few of the folks before getting into the question just marking it as duplicate however in this case the solution that they are referring with the below mentioned links won't work as I am using arrow functions and its changing the context. Please read the answers for the support.
Use normal function. When arrow syntax is used, this
inside it will refer to the enclosing context. Also, use change
event.
No binding of this
$("input[type='checkbox']").on('change', function() {
console.log("Checked Value 'is' :: ", $(this).is(':checked'));
console.log("Checked Value 'prop' :: ", $(this).prop('checked'));
});
Fiddle
$("input[type='checkbox']").on('change', function() {
console.log("Checked Value 'is' :: ", $(this).is(':checked'));
console.log("Checked Value 'prop' :: ", $(this).prop('checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="accept-t-and-c" /> I accept terms and conditions</p>
尝试下面的代码:
$("input[type='checkbox']").on('change', (e) => {
console.log("Checked Value 'is' :: ", e.currentTarget.checked);
})
如果您使用该语法,则需要将代码更改为
$document.ready(() => {
$("input[type='checkbox']").on('click', (e) => {
console.log("Checked Value 'is' :: ", $(e.target).is(':checked'));
console.log("Checked Value 'prop' :: ", $(e.target).prop('checked'));
})
})
链接地址: http://www.djcxy.com/p/55996.html
上一篇: jQuery:检查复选框是否被选中