Reputation: 25
I wish I could add a button in an innerHTML that when clicked on it starts a function.
var test = document.getElementById('test');
test.innerHTML += "<button onclick="
myFunction()
">Click me</button> ";
function myFunction() {
alert("hello");
}
<div id="test"> </div>
I would like to understand why this code does not work this way
Upvotes: 0
Views: 3456
Reputation: 1651
I see a few solutions here:
1. You use single quotes inside double quotes or vice versa
2. You escape the single/double quotes inside the string when using only single or double quotes
3. use jquery append
NOTE: witch JQuery append you can just insert another element of the HTML, so no worries about having wrong quotes/escaping characters etc..
var test = document.getElementById('test');
test.innerHTML += "<button onclick='myFunction()'>Click me</button>";
var test2 = document.getElementById('test2');
test2.innerHTML += "<button onclick=\"myFunction()\">Click me</button>";
$("#test3").append("<button onclick='myFunction()'>Click me</button>");
$("#test4").append($("#btn"));
function myFunction() {
alert("hello");
}
#test4 #btn {
display: block;
}
#btn{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
1:
<div id="test"></div>
2:
<div id="test2"></div>
3:
<div id="test3"></div>
4:
<div id="test4"></div>
<button id="btn" onclick='myFunction()'>Click me</button>
Upvotes: 0
Reputation: 27082
You have to use single/double qoutes, or escape them.
test.innerHTML += "<button onclick='myFunction()'>Click me</button> ";
OR
test.innerHTML += "<button onclick=\"myFunction()\">Click me</button> ";
Upvotes: 4