简体   繁体   中英

Radio button event listener is not fired when changed manually

I am using

document.getElementById('myId').checked = true;

to change which radio input/button should be checked.

It works fine, but I also have an event listener

document.getElementById('myId').onchange = function () {
  console.log(this.checked);
};

The problem is that the event listener is fired when I click the radio input/button, but it is not fired when I change the checked state with code.

From the docs :

The change event occurs when a control loses the input focus and its value has been modified since gaining focus. This event is valid for INPUT, SELECT, and TEXTAREA. element.

So the event will not fire when you are changing the value programatically. So what you can do is to fire the event programmatically calling the function.

var ele = document.getElementById('myId');
ele.checked = true;
ele.onchange.call(ele);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM