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

4 Answers 4

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>";
Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.