I create a button dynamically through javascript. When I click on it I get the mentioned error.
The button is created like this:
var button = document.createElement("Button");
button.setAttribute("onclick", "FollowUser('" + name + "')");
button.setAttribute("id", "FollowUserButton");
When debugging it, I’ve tried to figure out what goes wrong when I create it. It seems to be in the part where I make the onclick event. Nothing seems odd when I set the id.
This output is returned:
button {disabled: false, form: null, formAction: “https://localhost:44398/Home/UserProfile?name=Test”, …}
Advertisement
Answer
I’m providing my solution by presuming few things here. Please make sure to make the suitable changes in your code. The below code snippet will provide a base to the answer you want.
let name = "foo";
var button = document.createElement("BUTTON");
var text = document.createTextNode("Click me");
button.appendChild(text);
button.setAttribute("onclick", `FollowUser('${name}')`);
button.setAttribute("id", "FollowUserButton");
// Append this button to a node. For instance, append it to the body.
document.body.appendChild(button);
// Function added for testing onclick event.
function FollowUser(str) {
console.log(str);
}I’m using template literals here to make the code more readable and less chaotic.