cannot add onclick event to dynamically created button - javascript

I have a script that is meant to dynamically create row items. My problem is the creation of the last cell item, a button. I have tried using onclick, setAttribute and attachEvent. But either the button is created or the onclick event is launched in the addGarageRow() function which creates the button and not the onclick event of the created button itself
function addGarageRow(tableID)
{
var table=document.getElementById(tableID);
rownum = rownum + 1;
var rowCount=table.rows.length;
var row=table.insertRow(rowCount);
var cell1=row.insertCell(0);
var element1=document.createElement("input");
element1.type="checkbox";
element1.name="chk[]";
cell1.appendChild(element1);
var cell2=row.insertCell(1);
var element2=document.createElement("input");
element2.type="text";
element2.id=rownum;
element2.name="garage_for[]";
cell2.appendChild(element2);
var cell3=row.insertCell(2);
var element3=document.createElement("input");
element3.type="text";
element3.id="amount"+rownum;
element3.name="garage_amount[]";
cell3.appendChild(element3);
var cell4=row.insertCell(3);
var element4=document.createElement("input");
element4.setAttribute("type", "button");
element4.id=rownum;
//element4.name="voucher";
//element4.onclick = alert("test");
//element4.setAttribute("onClick", alert("test");
//element4.attachEvent('OnClick',Hi());
cell4.appendChild(element4);
}

The handler should be wrapped in a function. i.e:
element4.onclick = function(){
alert("test");
}

You have to wrap the function you would like to be executed when the onclick event fires inside a function block. Check it out here: http://jsfiddle.net/qbhfdkq3/

Related

How can I bind events to dynamically added textbox?

I am dynamically creating table rows and adding text boxes.
I added new row and added a event listener to it.
I also tried creating a cell and adding event listener to it.
I am using a Javascript function for this, but my function is invoked even before the
event is triggered from newly created html element.
In all cases the function is called as soon as dynamic element is created
Any help is appreciated.
Doesn't Work:
Try 1
function addnewrow()
{
var row = table.insertRow(x.rowIndex+1);
row.addEventListener("click", addme, false);
}
function addme()
{
alert("am called ");
}
Try 2
var t12=document.createElement("input");
t12.id = index+"q";
t12.name = index+"q";
cellnewrow2.appendChild(t12);
//cellnewrow2.addEventListener("click",addme(),false);
cellnewrow2.onclick =addme();
Your first example is actually correct. May be there are other ways for your question. But you can also use bindand refer your arguments or parameters with thiskeyword inside the function.
function addnewrow() {
var table = document.getElementById('tbl');
var row = table.insertRow(1);
row.innerHTML = "CLICK ME";
let arg = 1;
row.addEventListener("click", addme.bind(arg));
}
function addme() {
alert("am called with the argument: " + this);
}
addnewrow();
<table id="tbl">
<tr>
<td>Hello</td>
</tr>
</table>
You can't implement a function when you want it to be a callback function. With not considering the performance optimizing, it could be the very basic code for you as practice.
<html>
<body>
<button id='btn'>Click Me</button>
<div id='div'></div>
</body>
<script>
var count = 0;
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
var div = document.getElementById('div');
div.innerHTML += '<h2>' + count + '</h2>';
count++;
});
</script>
</html>

HTML DOM createElement() [duplicate]

I'm trying to use javascript to create a button that has a onclick event that calls a function defined in the head that takes in as parameter a dom object relative to the button. how do i do this?
ex:
<html>
<head> <script>function blah(obj){alert(obj.value)}</script></head>
<body>
<button onclick="blah(this.parentNode.value);"></button>
</body>
</html>
javascript:
var newButton = document.createElement("button");
???
in the end i want the new button to be the same as the existing one.
function createButton(context, func) {
var button = document.createElement("input");
button.type = "button";
button.value = "im a button";
button.onclick = func;
context.appendChild(button);
}
window.onload = function() {
createButton(document.body, function() {
highlight(this.parentNode.childNodes[1]);
// Example of different context, copied function etc
// createButton(this.parentNode, this.onclick);
});
};
Is that what you want?
You can also use the built-in setAttrbute javascript function.
var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")
Hope it will help

Including strings as parameters for a function chosen for .setAttribute to a button in javascript

I want to be able to pass along a string as a value for a button's onclick function using setAttribute. I am getting the error that "add is not defined" when I click on the button and I am not sure what I am doing wrong.
var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(AddString,SectorString)');
function AddOrDeleteDiv(AddString, SectorString) {
//code
}
Do not use content attribute event handlers! Use event listeners instead:
var addButton = document.createElement("button");
var addString = "add";
var sectorString = "1_1";
addButton.addEventListener('click', function() {
addOrDeleteDiv(addString, sectorString);
});
function addOrDeleteDiv(addString, sectorString) {
//code
}
Well js is known for not having nice methods for string joining and please try to use function parameter names not same as global variable names, it's not a nice thing to do.
var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(' + JSON.stringify(AddString) + ',' + JSON.stringify(SectorString) + ')');
function AddOrDeleteDiv(addStr, secStr) {
//code
}
or as #Thomas said you could use acutual javascript event handler like , not modifying attributes to assign event handler
AddButton.onclick = function(){AddOrDeleteDiv(AddString,SectorString);}

Events and handlers JavaScript

I am writing a code in which I want to display a word and sentence to my webpage when clicked(button). So far I have one text being displayed onto the page.I want to display the sentence after the text.The sentence is not displaying... anyone know why?
function handleButtonClick(){
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
var textInput = document.getElementById("word");
var termName = textInput.value;
var dt = document.createElement("dt");
dt.innerHTML = termName;
var dl = document.getElementById("p");
dl.appendChild(dt);
var textInput = document.getElementById("sentence");
var termDefine = textInput.value;
var dd = document.createElement("dd");
dd.innerHTML = termDefine;
var dl = document.getElementById("define");
dl.appendChild(d);
}
window.onload = handleButtonClick;
button.onclick = handleButtonClick;
supposed to be
button.addEventListener('click', handleButtonClick);
The second point is that the click event handler should be bound outside the function scope. Otherwise a new event will be bound every single time the function handleButtonClick fires.
var button = document.getElementById("addButton");
button.addEventListener('click', handleButtonClick);
function handleButtonClick() {
// Your other code here
// that excludes the click handler
}
And developer tools is your friend. Always use it to check for any errors.
In addition to what #sushanth already mentioned there is a typo in your code:
Instead of
dl.appendChild(d);
It should be
dl.appendChild(dd);

javascript function is not defined on button click

i am dynamically creating a button element and on its onclick event seting a function call but its always saying removeimg is not defined (removeimg is name of function being called on click of button). hers the code :
link :
http://shri-ram.lifekloud.com/pilot/step4.php
(tab add delete photos)
function removeimg(){
//make request to remove the name
document.getElementById(name).style.display = 'none';
document.getElementById(btn12).style.display = 'none';
}
function showUploadedItem (source) {
var list = document.getElementById("image-listalbum"),
li = document.createElement("li"),
img = document.createElement("img");
var btn = document.createElement('input');
btn.setAttribute("type", "button");
btn.setAttribute("value", "Remove");
btn.setAttribute("class", "t-button");
var btnId = "btn" + source + "";
btn.setAttribute("id", btnId);
var func = "removeimg()";
btn.setAttribute("onclick", func);
img.src = 'uploads/'+source;
li.appendChild(img);
li.appendChild(btn);
list.appendChild(li);
}
Try
btn.onclick = removeimg;
rather than the string version you're doing.
Functions in Javascript have a scope, because they are essentially the same as any other Object. Since your function is defined inside the $(document).ready(); function it only exists in that scope. You'll have to declare it outside the ready() function to use it on the click of a button.

Categories