shou2017.com
JP

JavaScript: How to Add onclick to Dynamically Generated Inputs

Sun Dec 1, 2019
Sat Aug 10, 2024

I got stuck trying to add an onclick to an input tag in the same way you would add a className or textContent to a div tag, so I’m making a note.

This doesn’t work:

input.onclick = 'test()';

You’ll get an error: Assigned expression type string is not assignable to type(this.GlobalEventHandlers, ev: MouseEvent) => any.

The correct approach is:

 input.onclick = function() {
     userSelected = input.value;
     if(list[i].correctAnswer === userSelected){
         console.log('Correct');
     } else {
         console.log('Incorrect');
     }
 };

You need to assign a function to onclick. In the example, userSelected is declared with let.

If you want to use location.href, simply include it inside the function.

    backButton.onclick = function () {
        location.href='../sample/index.html'
    }

改訂新版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで

See Also