Why does the preventDefault function on the checkbox return true for the checked attribute?

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

Let's say I have a checkbox for entering an element of type with an eventlistener attached to it that listens for the click event. I disable the default behavior of this flag and register the flagged state of the flag, which will always return true.

The visual representation of the flag tells me that it has not been verified. Therefore, I would suggest that the checked state will return false. I am sure that this must be something stupid, and I completely understand nothing. The funny thing is that I myself register the event. Inside the target property, the checked property is false, as expected.

From my understanding, prevention by default cancels the event without stopping the distribution, and what exactly happens here?

It would be great if someone could enlighten me on this. Here is an example.

var checkbox = document.getElementsByTagName('input')[0],
    output = document.getElementById('output');

checkbox.addEventListener('click', function(evt) {
  evt.preventDefault();
  output.innerHTML = "Checkbox checked attribute is " + this.checked;
  console.log(this.checked, evt.target.checked);
  console.log(evt);
}, false);
<input type="checkbox" id="my-checkbox" />
<label for="my-checkbox">Checkbox with preventDefault().</label>
<div id="output"></div>
Run codeHide result
+4
source share
2 answers

Actually, the result checkedin the handler click depends on the implementation .

As I tested in several browsers, Chrome / Firefox / Safari / Opera will always return true in this case, but the behavior of IE / Edge is a bit strange if you keep clicking on this checkbox element.

And I found this paragraph in the specification, which could be an explanation for this inconsistency:

. , "" "", . , . , .

preventDefault, IE/Edge , .

, IE/Edge... Microsoft Connect.


, , Chrome , :

HTML Spec input[type=checkbox] , Activation. .

( , , , )

+4

w3schools " preventDefault() , , , , , ". ( this console.log( "cancelable?" + Evt.cancelable);. , , , click checkbox , true false, , , . ; , preventDefault() .

checked = true; unchecked = false. EventListener , , , , evt.preventDefault() , console.log(this.checked, evt.target.checked); "", "unchecked" , eventListener . , preventDefault ( ) () , .

The image represents some of the steps described in the paragraph above.

0

All Articles