Hello interested in the question of how to trigger an event on the checkbox of the form that would enter into the console and a check mark appeared.

var elem = document.forms[0][0] var event = document.createEvent('HTMLEvents') event.initEvent("change", false, false); elem.dispatchEvent(event) 

this does not work, and the following also does not work:

 elem = document.forms[0][0] var event = new Event("change"); elem.dispatchEvent(event); 

But as I understand it, the last option is to set up a custom event, but at the same time, the software form submit works:

 elem = document.forms[0] var event = new Event("submit"); elem.dispatchEvent(event); 

And with the checkbox, not only change , but focus does not work (construction: var elem = document.forms[0][0]; elem.focus() generally returns undefined).

What am I doing wrong? How to call a chande on the checkbox or focus at least?

PS I know how to do it on jQuery, pure JS (Chrome browser) is interested.

  • Blunted change is the same when already changed is called, but in Fucus is still not clear - Jarry Roxwell
  • why do you think the change event doesn't work? add an event handler for this event and see that everything works - Grundy
  • I agree, it works. However, like onfocus but the visual focus is not displayed, while clicking the tab, the checkbox lights up - Jarry Roxwell

2 answers 2

The issue is confused cause and effect.

Events occur after actions have taken place, so simply by triggering an event, nothing happens except to call the event handler for this event, if it was.

Because of this, it seems that the change event does not occur. In order to manually change the state of the checkbox, it is necessary to change the checked property to it, if you want the handlers to be called up after this, you need to send the corresponding event.

 elem = document.forms[0][0] elem.onchange = function() { console.log('change event'); } elem.checked = true; var event = new Event("change"); elem.dispatchEvent(event); 
 <form> <input type="checkbox" /> </form> 

With the focus, the situation is slightly different, since the elements have a direct focus method.

 elem = document.forms[0][0] elem.onfocus = function() { console.log('focus event'); } elem.focus(); 
 input:focus + span::before { content: 'focus'; } 
 <form> <input type="checkbox" /> <span></span> </form> 

  • In my FF does not work ... - Qwertiy
  • what exactly? and what version of FF? - Grundy
  • The second snippet. FF 50 beta 4, for example. And in chrome works. - Qwertiy

 var input = document.querySelector('input'); input.addEventListener('change', function (event) { console.log(event.target.checked, '(from handler)'); }); console.log(input.checked); input.click(); console.log(input.checked); 
 <input type=checkbox>