hellzone
hellzone

Reputation: 5236

How to add onclick function from javascript?

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>"

Upvotes: 0

Views: 383

Answers (4)

dzuncoi
dzuncoi

Reputation: 31

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")
})

Upvotes: 0

farzane
farzane

Reputation: 339

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

Upvotes: 0

Jyothi Babu Araja
Jyothi Babu Araja

Reputation: 10282

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>

Upvotes: 1

Aycan Yaşıt
Aycan Yaşıt

Reputation: 2104

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>";

Upvotes: 2

Related Questions