for some reason this code doesn't properly get the checked property of the checkbox, instead it always false. I was expecting it to show whether the checkbox was checked. What am I missing? Thanks
const clickArray = document.querySelectorAll("input")
const changeStyle = style => {
return (() => console.log(style))
}
clickArray.forEach(
(item, index) => {
item.addEventListener('click', changeStyle(item.checked))
}
)
<label for="chk1">
<input type="checkbox" name="chk1" value="chk1">
Bold
</label>
<label for="chk2">
<input type="checkbox" name="chk2" value="chk2">
Italic
</label>
<label for="chk3">
<input type="checkbox" name="chk3" value="chk3">
Underline
</label> const click
SOLVED, In your case the function call is loosing the context, As you are using eventlisteners, use event to perform any checks, not element, as it will bind the old context of the element to the function.
clickArray = document.querySelectorAll("input");
const changeStyle = style => {
console.log(style);
}
clickArray.forEach(
(item, index) => {
item.addEventListener('click', function (e) { changeStyle(e.target.checked) })
}
)
This element:
<input type="checkbox" name="chk1" value="chk1">
will report .checked = false because it does not have the attribute checked. If you want to have the .checked = true the element should be
<input type="checkbox" name="chk1" value="chk1" checked="checked">
Notice: an <input> of type=checkbox has no use of the attribute value. Thus, it is ignored. It has no effect on its .checked property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With