How can I bind events to dynamically added textbox? - javascript

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>

Related

Using addEventListener() in a for loop with various listeners

I'm trying to add listeners to a number of buttons using a for loop. The appropriate listener for each button is indicated by the ID attribute of the button. Button IDs follow the form "button-[listenerName]". I get the list of all my button elements using querySelectorAll(), and then I iterate through that list, slicing out the name of each listener from the name of each button element. Then, I use the name of the listener with addEventListener() in an attempt to associate that button with its listener.
<!DOCTYPE html>
<html>
<body>
<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>
<p id="demo"></p>
<script>
var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
button.addEventListener("click", listenerName);
}
var listener1 = function() {
document.getElementById('demo').innerHtml = "1";
}
var listener2 = function() {
document.getElementById('demo').innerHtml = "2";
}
var listener3 = function() {
document.getElementById('demo').innerHtml = "3";
}
var listener4 = function() {
document.getElementById('demo').innerHtml = "4";
}
</script>
</body>
</html>
Unfortunately, it doesn't work. What's up with that? Thank you.
There are 3 issues with your code:
In your for loop, you are essentially attaching strings as eventlisteners. You need to access your event listeners from the string you have.
Since you eventlisteners are declared in the global scopre, you can use window to access them:
button.addEventListener("click", window[listenerName]);
You are attaching the event listeners before declaring them. You need to declare listener1 and so on before your for loop
innerHtml does not exist. The right syntax is innerHTML
Here is a working example:
<!DOCTYPE html>
<html>
<body>
<button id="button-listener1">Try 1</button>
<button id="button-listener2">Try 2</button>
<button id="button-listener3">Try 3</button>
<button id="button-listener4">Try 4</button>
<p id="demo"></p>
<script>
var listener1 = function() {
document.getElementById('demo').innerHTML = "1";
}
var listener2 = function() {
document.getElementById('demo').innerHTML = "2";
}
var listener3 = function() {
document.getElementById('demo').innerHTML = "3";
}
var listener4 = function() {
document.getElementById('demo').innerHTML = "4";
}
var selector = "[id^=button]";
var allButtons = document.querySelectorAll(selector);
for (var button of allButtons) {
var listenerName = button.id.slice(button.id.lastIndexOf("-")+1);
button.addEventListener("click", window[listenerName]);
}
</script>
</body>
</html>
your line button.addEventListener("click", listenerName); tried to add a function called listenerName to the click event, and since listenerName is a variable and not a function, it doesn't work.
You could use an array of function to make it work instead.
var array_of_functions = [
'listener1' : listener1,
'listener2' : listener2,
'listener3' : listener3,
'listener4' : listener4
]
and then in your loop you could create the listener by giving the right function:
button.addEventListener("click", array_of_functions[listenerName]);
Also, make sure you create the function and the array before running the loop or they won't exist yet when the code runs.
There's a slightly easier way to do this - just have one function that handles the event:
for (var button of allButtons) {
button.addEventListener("click", handleClick, false);
}
function handleClick() {
var id = this.id.match(/button-listener(\d)/)[1];
document.getElementById('demo').innerHTML = id;
}
DEMO
Or, you can change your loop like this and your code will work
allButtons.forEach(function (button, i) {
var listenerName = button.id.slice(button.id.lastIndexOf("-") + 1);
button.addEventListener("click", function () {
document.getElementById('demo').innerHTML = i + 1;
});
});

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

cannot add onclick event to dynamically created button

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/

JavaScript to add table row onclick events

I'm new to Javascript. I want to add onclick events to table rows. I'm not using JQuery.
I loop thru the rows and use a closure to make sure I have the state of the outer function for each row.
The looping works. Using alerts, I see the function being assigned for each iteration. But when I click the row, no alert is displayed.
Below is the HTML and code that can be loaded.
Why are the table row events not working?
<!doctype html>
<html lang="en">
<body>
<script>
function example4() {
var table = document.getElementById("tableid4");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
var curRow = table.rows[i];
//get cell data from first col of row
var cell = curRow.getElementsByTagName("td")[0];
curRow.onclick = function() {
return function() {
alert("row " + i + " data="+ cell.innerHTML);
};
};
}
}
function init() { example4(); }
window.onload = init;
</script>
<div>
Use loop to assign onclick handler for each table row in DOM. Uses Closure.
<table id="tableid4" border=1>
<tbody>
<tr><td>Item one</td></tr>
<tr><td>Item two</td></tr>
<tr><td>Item three</td></tr>
</tbody>
</table>
</div>
</body>
</html>
This seem to be the canonical way
DEMO
function example4() {
var table = document.getElementById("tableid4");
var rows = table.rows; // or table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
rows[i].onclick = (function() { // closure
var cnt = i; // save the counter to use in the function
return function() {
alert("row"+cnt+" data="+this.cells[0].innerHTML);
}
})(i);
}
}
window.onload = function() { example4(); }​
UPDATE: #ParkerSuperstar suggested that the i in (i) is not needed.
I have not tested this but his fiddle seems to work.
I'm not quite sure why you're using a closure here, could you be a bit more elaborate?
The reason you're not seeing the desired alert is because within the onclick function, you're returning another function. I.e:
window.onload = function() {
return function() {
alert("Closure... why?");
};
};
Something like this won't really work because you're never calling the nested function... try it without using the closure, or comment explaining why you want a closure because you're explanation didn't make much sense to me.
You just have to remove an extra function and script will be like this
<script>
function example4() {
var table = document.getElementById("tableid4");
cells = table.getElementsByTagName('td');
for (var i=0,len=cells.length; i<len; i++){
cells[i].onclick = function(){
alert(this.innerHTML);
}
}
}
function init() { example4(); }
window.onload = init;
</script>

Categories