onChange in createElement not working. React

Viewed 37

Using react and tried to create an element with createElement.

const inputForEnglish = document.createElement("input");
inputForEnglish.type = "text";
inputForEnglish.placeholder = "English";
inputForEnglish.dataset.answernumber = answers.children.length + 1;
inputForEnglish.dataset.textfield = "english";
inputForEnglish.onChange = (e) => detectAnswerChange(e);

The last line doesn't work. I have a function called "detectAnswerChange()" and it takes event as parameter. The onChange works completely fine when it's done directly to an element.

I also tried inputForEnglish.onchange = "detectAnswerChange()", it doesn't work.

It creates the element and all the above things works completely fine, but the inputForEnglish.onChange = (e) => detectAnswerChange(e); doesn't work.

2 Answers

It's all small letters. Use this:

inputForEnglish.onchange = (e) => detectAnswerChange(e);
inputForEnglish.oninput=(e)=>{
    //runs when the input changes
    console.log(e.target.value)
}
inputForEnglish.onchange=(e)=>{
    //runs only when the input is out of focus
    console.log(e.target.value)
}

use oninput for inputs

Related