Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checkbox .checked property always false

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
like image 860
Rik Avatar asked Dec 17 '25 07:12

Rik


2 Answers

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) })
  }
)
like image 134
Dip686 Avatar answered Dec 19 '25 22:12

Dip686


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.

like image 43
Ahmad Avatar answered Dec 19 '25 22:12

Ahmad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!