'how to create <input onchange='myFunction()' /> dynamically with function
I know that you can use document.createElement for this but I get a domexception from doing this:
document.createElement("<input onchange='myFunction()' />");
Error:
Uncaught DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('<input onchange='myFunction()' />') is not a valid name.
Do you know how to create an element dynamically with a function?
Solution 1:[1]
You should make it in 3 times :
- First creating the element
- Then adding the function
- Finally adding it to the dom
const myFunction = () => {
console.log("hello world")
}
const btn = document.createElement('button')
btn.innerText = "MyBtn"
btn.addEventListener('click', myFunction)
document.body.appendChild(btn)
Solution 2:[2]
Sorry I was too quick to ask for help. But this is the answer:
newInput3.onchange = myFunction;
myFunction should not be an actual string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | RenaudC5 |
Solution 2 | Iskooolar2 iskoolar2 |