0

I want to create a button and add an onclick function to this button with javascript but there is a problem with onclick function. When I add button as below code I can't see quotation marks on Chrome. How can I add an onclick function with arguments?

myButton+= "<button onclick='addNewproperty('" + property + "','" + entry + "')' class='btn grey btn-circle' style='font-size: x-small; float: left'><i class='fa fa-times'></i>";
myButton+= entry.length > 12 ? entry.substring(0,12) + "..." : entry;
myButton+= "</button>"
hellzone
  • 5,393
  • 25
  • 82
  • 148

4 Answers4

2

You may escape quotes. Since you were using same type of quotes as wrapper and inner quotes, it was actually acting like <button onclick="addNewproperty(".

myButton+= "<button onclick=\"addNewproperty('" + property + "','" + entry + "')\" class='btn grey btn-circle' style='font-size: x-small; float: left'><i class='fa fa-times'></i>";
myButton+= entry.length > 12 ? entry.substring(0,12) + "..." : entry;
myButton+= "</button>";
Aycan Yaşıt
  • 2,106
  • 4
  • 34
  • 40
1

You can also use backticks ` to wrap your variables.

var hello = "Hello";
var myButton = "";
myButton+= "<button onclick='alert(`" + hello + "`)' class='btn grey btn-circle' style='font-size: x-small; float: left'><i class='fa fa-times'></i>";
myButton+= "</button>"

document.getElementById("div").innerHTML = myButton
<div id="div">

</div>
Jyothi Babu Araja
  • 10,076
  • 3
  • 31
  • 38
0

based on this answer and my self experience sometimes you shoud use onClick instead of onclick.

Community
  • 1
  • 1
farzane
  • 329
  • 2
  • 13
0

For easier approach, you can add an id to your button element, eg:

myButton += "<button id='someId'>"

Then you can add onClick or any events to your element by:

document.getElementById("someId").addEventListener('click', function(){
   alert("Button clicked")
})
dzuncoi
  • 31
  • 7