Why does preventDefault on checkbox click event returns true for the checked attribute?

后端 未结 2 1204
孤城傲影
孤城傲影 2020-12-19 09:03

I am just curious and need some explanation on the following situation.

Let\'s say i have an input element of type checkbox with an eventlistener attached to it, lis

2条回答
  •  鱼传尺愫
    2020-12-19 09:45

    According to w3schools "The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur." The click event is cancelable (you can check it like this console.log("cancelable? "+ evt.cancelable);. So from what I understand, the default behavior of click event for a checkbox object is to read the current state of a checkbox and alternate between true and false, consequently changing its state to checked and unchecked. In shorter words the default behavior is toggling; therefore, preventDefault() cancels that behavior.

    In relation to checkboxes checked = true; unchecked = false.If you try to debug and follow eventListener step by step you will see that once you in it the unchecked box becomes "checked" even after stepping on evt.preventDefault() so when you call console.log(this.checked, evt.target.checked); at that time for the compiler your box is "checked", the checkbox goes back to "unchecked" state only when eventListener done execution. From this I can conclude that in case with checkboxes preventDefault() is actually activated(executed) at very last after all calls within event listener is executed.

提交回复
热议问题