简体   繁体   中英

Radio input checked with keyboard shortcut doesn't trigger event change

I have added a keyboard shortcut to my script so that when I press ctrl + 1 the first "source" radio input is checked :

    if (e.key == "1" && e.ctrlKey) {
        document.getElementsByName("source")[0].checked = true;

    }

So far everythin is good. I have added an event listener so that when the state of my radio input are changed, then several things happen. But this event listener isn't triggered when I press ctrl+1 even thought the state of the radio input is changed (I can see the color of the input changing). If click manually on the radio input then the event listener is working:

var radiosource = document.getElementsByName("source");
for (var i = 0; i < radiosource.length; i++) {
    radiosource[i].addEventListener('change', function (e) {
        var input_changed_id = e.target.id;
        if (input_changed_id.includes("en")) {
            document.getElementById("fr_target").checked = true;
            current_target = "fr";
        }
        if (input_changed_id.includes("fr")) {
            document.getElementById("en_target").checked = true;
            current_target = "en";
        }
        translate();
    });
}

Here is the full script (cf lines 119 and lines 49 and 322)

It won't trigger if you change the checked value manually but your event will trigger if you simulate the click on the radio button using .click() .

So just update your keyboard shortcut script to this:

if (e.key == "1" && e.ctrlKey) {
  document.getElementsByName("source")[0].click();
}

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