how to create several buttons dynamically in for loop - javascript

Here id my code. I want to append 4 buttons inside the specific div. In the other words, I want to put these 4 buttons inside ''. Now it works but they are not inside the div.
getmyItems function is a function that contains an array of information like: title, description , age ,... .
Help
getmyItems(param, function(data) {
var mtItem = JSON.stringify(data);
myItem = JSON.parse(mtItem);
var Item = document.getElementById('myItems');
for (var i = 0; i < myItem.results.length; i++) {
var buffer = "";
buffer += '<div class="act-time">';
buffer += '<div class="activity-body act-in">';
buffer += '<span class="arrow"></span>';
buffer += '<div class="text">';
buffer += '<p class="attribution">';
buffer += ''+myItem.results[i].title+'';
buffer += myItem.results[i].description;
buffer += '</p>';
buffer += '</div>';
buffer += '</div>';
buffer += '</div>';
var div = document.createElement('div');
div.innerHTML = buffer;
//var elem = div.firstChild;
Item.appendChild(div);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'btn btn-danger');
btn.value = "Delete";
btn.onclick = (function(i) {
return function() {
var c=confirm('Are you Sure? ');
if (c==true)
doDelete(myItem.results[i].item_id);
};
})(i);
Item.appendChild(btn);
var show_btn=document.createElement('input');
show_btn.setAttribute('type','button');
show_btn.setAttribute('class','btn btn-primary');
show_btn.value="ShowInDetail";
show_btn.onclick=(function(i){
return function(){
showInDetail(myItem.results[i]);
window.location='showInDetail.html';
};
})(i);
Item.appendChild(show_btn);
var extend_btn=document.createElement('input');
extend_btn.setAttribute('class','btn btn-warning');
extend_btn.setAttribute('type','button');
extend_btn.value="Extend";
extend_btn.onclick=(function(i){
return function(){
extendItem(myItem.results[i]);
window.location='extendItem.html';
};
})(i);
Item.appendChild(extend_btn);
var bookmark=document.createElement('input');
bookmark.setAttribute('type','button');
bookmark.setAttribute('class','btn btn-primary');
bookmark.value='Bookmark';
bookmark.onclick=(function(i){
return function(){
var p={user_id:localStorage.getItem('user_id')};
window.localStorage.setItem('this_item_id', myItem.results[i].item_id);
getBookmarks(p, function(d){
var bk=JSON.stringify(d);
bk=JSON.parse(bk);
if(bk.results){
var l=0;
for(var j in bk.results){
if(bk.results[j].item_id==localStorage.getItem('this_item_id')){
removeBookmark(bk.results[j]);
l=1;
}
}if(l==0){
addBookmark(myItem.results[i]);
}
}else{
addBookmark(myItem.results[i]);
}
});
};
})(i);
Item.appendChild(bookmark);
//document.getElementById(i).appendChild(btn);
}
});

In what specific div do you want them? So far, in this way the four buttons are inside the myItens div see in the fiddle and in the code below.
var getmyItems = function(data) {
var item = document.getElementById('myItems');
for (var i = 0; i < data.length; i++) {
var result = data[i];
// creation of the buffer outer div
var buffer = document.createElement('div');
buffer.className = 'act-time';
//creation of de activity-body
var activity = document.createElement('div');
activity.className = 'activity-body act-in';
//creation of the first span
var arrow = document.createElement('span');
arrow.className = 'arrow';
//creation of the most inner div
var textDiv = document.createElement('div');
textDiv.className = 'text';
//creation of the content of the most inner div
var attribution = '';
attribution += '<p class="attribution">';
attribution += '' + result.title + '';
attribution += result.description;
attribution += '</p>';
//initialize the text div
textDiv.innerHTML = attribution;
//put the arrow span inside the activity div
activity.appendChild(arrow);
// put the text div inside the activity div
activity.appendChild(textDiv);
//put the activity inside the buffer div
// each time appendChild is applied the element is attach tho the end of the target element
buffer.appendChild(activity);
var div = document.createElement('div');
div.appendChild(buffer);
item.appendChild(div);
var btn = document.createElement('input');
btn.setAttribute('type', 'button');
btn.setAttribute('class', 'btn btn-danger');
btn.value = "Delete";
btn.onclick = (function(i) {
return function() {
var c = confirm('Are you Sure? ');
if (c === true) {
//do something;
};
};
})(i);
// now that all div are created you can choose which div you want to put the button inside.
// in this I chose the buffer.
buffer.appendChild(btn);
var showBtn = document.createElement('input');
showBtn.setAttribute('type', 'button');
showBtn.setAttribute('class', 'btn btn-primary');
showBtn.value = "ShowInDetail";
showBtn.onclick = (function(i) {
return function() {
window.location = 'showInDetail.html';
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(showBtn);
var extendBtn = document.createElement('input');
extendBtn.setAttribute('class', 'btn btn-warning');
extendBtn.setAttribute('type', 'button');
extendBtn.value = "Extend";
extendBtn.onclick = (function(i) {
return function() {
window.location = 'extendItem.html';
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(extendBtn);
var bookmark = document.createElement('input');
bookmark.setAttribute('type', 'button');
bookmark.setAttribute('class', 'btn btn-primary');
bookmark.value = 'Bookmark';
bookmark.onclick = (function(i) {
return function() {
var p = { user_id: localStorage.getItem('user_id') };
window.localStorage.setItem('this_item_id', myItem.results[i].item_id);
//do something
};
})(i);
// button is append to the end of the buffer
buffer.appendChild(bookmark);
}
};
var myItem = [{ title: 'person', description: 'familyName' }, { title: 'ohterPerson', description: 'otherFamilyName' }];
getmyItems(myItem);

Related

JavaScript adding event on element generated element with innerHtml

I want to add an event on an element does doesn't exist in the original HTML (created with innerHtml). When i click nothing happens.
const btnRemove = document.getElementById("remove");
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
});
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
I want to add a click event on the element with id remove.
Another way to do that is creating the elements instead of use the HTML code and a later search. This maybe useful if you, for example, don't want to add an id to the remove tag
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = document.createElement("div");
div.className = "v1";
service.appendChild(div);
var p1 = document.createElement("p");
p1.className = "v3-text";
div.appendChild(p1);
var p1Text = document.createTextNode("Mown Lawn ");
p1.appendChild(p1Text);
var p1Span = document.createElement("span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
p1.appendChild(p1Span);
var p2 = document.createElement("p");
p2.className = "v3-dollar";
p2.innerHTML = "<span>$</span>20";
div.appendChild(p2);
sMow = false;
total += 20;
totalC();
}
});
As you can see, creating the elements allow you do whatever you want with it. It's longer but you can use a helper function like this:
function appendTag(parent, tagName, className) {
var tag = document.createElement(tagName);
if (className)
tag.className = className;
parent.appendChild(tag);
return tag;
}
And rewrite as:
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = appendTag(service, "div", "v1");
var p1 = appendTag(div, "p", "v3-text");
p1.appendChild(document.createTextNode("Mown Lawn "));
var p1Span = appendTag(p1, "span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
var p2 = appendTag(p1, "p", "v3-dollar");
p2.innerHTML = "<span>$</span>20";
sMow = false;
total += 20;
totalC();
}
});
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
const btnRemove = document.getElementById("remove");
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
});
var btnremove = document.getElementById("remove");
write this before starting click event

trigger js alerts from es6 in iOS safari not working

I have a website that triggers an alert when items are added to the cart. I'm using javascript ES6, html5.
I'm dynamically creating bootstrap styled cards with menu items on the page and a add to cart button. when the add to cart button is pressed an alert is triggered.
The alert attempts to trigger on iOS 13.x.x safari but doesn't show. I attempted to set a timeout, but that didn't work. It has to be the way it's being called. I really don't know what to try next. I read that user navigation (back, forward) can break alerts. In the 'addEventListener' of the 'btn' towards the bottom of this horrific method is where the problem arises. Why is this not working on safari mobile?
createMenuCard(menu){
var heading = document.getElementById("concession-name");
heading.innerText = menu.menus.menu.concessionName;
var card = null;
var body = null;
var lsgroup = null;
for(var i = 0; i < menu.menus.menu.categories.length; i++){
for(var j = 0; j < menu.menus.menu.categories[i].menuItems.length; j++){
this.card = document.createElement('div');
this.card.className = 'card';
this.card.setAttribute('id', this.uuidv4());
this.card.setAttribute('style', 'width: 20rem;');
this.body = document.createElement('div');
this.body.className = 'card-body';
var title = document.createElement('div');
title.className = 'card-title';
title.innerText = menu.menus.menu.categories[i].menuItems[j].name;
this.body.appendChild(title);
this.lsgroup = document.createElement('div');
this.lsgroup.className = "list-group";
this.body.appendChild(this.lsgroup);
for(var k = 0; k < menu.menus.menu.categories[i].menuItems[j].subItems.length; k++){
if(menu.menus.menu.categories[i].menuItems[j].subItems[k].name === "")
{
var id = this.uuidv4();
var input = document.createElement("input");
input.setAttribute("type", "checkbox");
input.setAttribute("name", "");
input.setAttribute("id", id);
input.setAttribute("value", menu.menus.menu.categories[i].menuItems[j].name);
input.setAttribute("price", menu.menus.menu.categories[i].menuItems[j].subItems[k].price);
this.lsgroup.appendChild(input);
// label
var label = document.createElement("label");
label.className = "list-group-item";
label.setAttribute("for", id);
label.innerText = menu.menus.menu.categories[i].menuItems[j].subItems[k].price + " " + menu.menus.menu.categories[i].menuItems[j].name;
this.lsgroup.appendChild(label);
}
else
{
var id = this.uuidv4();
// input
var input = document.createElement("input");
input.setAttribute("type", "checkbox");
input.setAttribute("name", "");
input.setAttribute("id", id);
input.setAttribute("value", menu.menus.menu.categories[i].menuItems[j].subItems[k].name);
input.setAttribute("price", menu.menus.menu.categories[i].menuItems[j].subItems[k].price);
this.lsgroup.appendChild(input);
// label
var label = document.createElement("label");
label.className = "list-group-item";
label.setAttribute("for", id);
label.innerText = menu.menus.menu.categories[i].menuItems[j].subItems[k].price + " " +menu.menus.menu.categories[i].menuItems[j].subItems[k].name;
this.lsgroup.appendChild(label);
}
}
var btn = document.createElement('a');
btn.setAttribute("href", "#"); // javascript:toCart()
btn.addEventListener("click", (e)=> {
var inputs = e.path[2].querySelector("div > div.list-group").getElementsByTagName("input");
var description = e.path[2].querySelector("div > div.card-title").innerText;
for(var l = 0; l < inputs.length; l++){
if(inputs[l].checked === true){
var obj = {
option : inputs[l].value,
price : inputs[l].getAttribute("price")
};
setTimeout(function(){
window.alert("Added: " + description + " to cart");
}, 300);
//window.alert("Added: " + description + " to cart");
description += " " + obj.option;
var appItem = new AppItems(description, obj.price, 1);
cart.addItem(appItem);
}
}
});
btn.className = "btn btn-primary";
btn.innerText = "Add To Cart";
this.body.appendChild(btn);
this.card.appendChild(this.body);
var container = document.getElementById('cards');
container.appendChild(this.card);
}
}
var chk = document.getElementById("checkout");
chk.addEventListener("click", (e)=> {
cart.save();
window.open("./cart.html","_self");
});
}

How to create divs dynamically using JavaScript?

I want to create my divs in a way to access my JSON data and display all every time I create a new div. I have my first div display information through my JSON. This is what I got so far:
document.addEventListener('DOMContentLoaded', function() {
function function_name(data) {
return {data: ['nombre','telefono'],pie: 'texto'};
}
function _data(info) {
return info;
}
(function() {
var obj = {
id: 'id',
nombre: 'pepe',
telefono: '6691296347'
};
var body = document.getElementsByTagName('body')[0];
var div = document.createElement('div');
var p = document.createElement('p');
var span = document.createElement('span');
var _p = document.createElement('p');
var _span = document.createElement('span');
var btn = document.createElement('button');
var p_ = document.createElement('p');
var span_ = document.createElement('span');
p_.textContent = 'ID: ';
div.appendChild(p_);
p_.appendChild(span_);
span_.textContent = obj.id;
body.appendChild(div);
data = JSON.stringify(_data(obj));
p.textContent = 'nombre: ';
div.appendChild(p);
p.appendChild(span);
span.textContent = obj.nombre;
_p.textContent = 'Telefono: ';
div.appendChild(_p);
_p.appendChild(_span);
_span.textContent = obj.telefono;
div.appendChild(btn);
btn.textContent = 'button';
btn.setAttribute("id","id");
btn.addEventListener('click',function (e) {
console.log(_data(obj));
});
})();
});
I do not know if the is a basic javascript way to do that ...but i use jquery to add data to every new div element
data = {"obj" : [{"name" : "John"}]}
Json that returns object
$.each(data.obj, function(i, message){
var htmlMessage = "";
htmlMessage += "<div>";
htmlMessage += "<p>";
htmlMessage += "<span>";
htmlMessage += message.name;
htmlMessage += "</div>";
htmlMessage += "</p>";
htmlMessage += "</span>";
$("#body")[0].innerHtml += htmlMessage;
});
You can create a custom function for creating elements. For example:
// creating elements function
function createEl(config){
config = config || {};
if(!config.type) throw new Error('config type required!');
var new_el = document.createElement(config.type);
// check text param
if(config.text) new_el.textContent = config.text;
// maybe check for other element attributes (id, class, etc)
// ...
return new_el;
}
// some code
// ...
var obj = {
id: 'id',
nombre: 'pepe',
telefono: '6691296347'
};
var body = document.getElementsByTagName('body')[0];
var div = createEl({ type: 'div' });
var p = createEl({ type: 'p', text: 'nombre: '});
var span = createEl({ type: 'span', text: obj.nombre});
// other elements
// ...
// and then append
p.appendChild(span);
div.appendChild(p);
body.appendChild(div);
// ...

Function to hide/show only one DIV at a time

I currently have a JavaScript that is looking at a SharePoint list, and pulling back all of the items that meet the criteria in the REST call.
It currently creates DIVs and appends them to a wrapper DIV. The intention of the button is to show/hide the sub-DIVs.
Right now, when I click any of the buttons that are produced, it expands all of the hidden divs. What I'm trying to accomplish is to be able to click each respective button and have its nested div show/hide.
Here is my code:
var listName = "announcement";
var titleField = "Title";
var tipField = "Quote";
var dateFieldFrom = "DateFrom";
var dateFieldTo = "DateTo";
var category = "category";
var noteField = "note";
var query = "/_api/Web/Lists/GetByTitle('" + listName + "')/items?$select=" + titleField + "," + dateFieldTo + "," + dateFieldFrom + "," + category + "," + noteField + "," + tipField;
var today = new Date();
var btnClass = "toggle"
todayString = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
//This is the query filter string where we compare the values in the 2 date fields against the current date
query += "&$filter=('" + todayString + "' ge " + dateFieldFrom + " ) and (" + dateFieldTo + " ge '" + todayString + "')";;
var call = $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function(data, textStatus, jqXHR) {
var divCount = data.d.results.length;
for (var i = 0; i < divCount; i++) {
var tip = data.d.results[i][tipField]; //this is where it looks at the quote field to determine what quote to place in the current dynamically created DIV
var cat = data.d.results[i][category]; //this is where it looks at the category field to determine what color to style the background of the current dynamically created DIV
var message = data.d.results[i][noteField];
var ID = "NewDiv-" + i
var PID = "P-" + i
var BID = "btn-" + i
// Create Message DIV
var element = document.createElement("div"); //This is the creation of the dynamic DIV
element.id = ID //This is assigning a DIV an ID
element.appendChild(document.createTextNode(tip));
// Create Inner message DIV
var innerDiv = document.createElement("div"); // Create a <div> element//New Code
innerDiv.id = PID
innerDiv.appendChild(document.createTextNode(message));
// Create button to show/hide the div
var btn = document.createElement("BUTTON");
btn.id = BID
btn.appendChild(document.createTextNode("show/hide message below"));
btn.className = btnClass
// Append Inner DIVs
document.getElementById('wrapper').appendChild(element); //This is the parent DIV element that all newly created DIVs get created into
document.getElementById(ID).appendChild(btn); // Append the button to the newly created DIV
document.getElementById(ID).appendChild(innerDiv); //This is the message that appears after the newly created DIVs
if (cat == 'Information') {
document.getElementById(ID).style.backgroundColor = '#d9edf7'; //Blue Color
document.getElementById(PID).style.backgroundColor = '#d9edf7'; //Blue Color
document.getElementById(PID).style.margin = '3px';
document.getElementById(BID).style.backgroundColor = '#d9edf7';
document.getElementById(BID).style.border = 'none';
innerDiv.className = "alert alert-info"
element.className = "alert alert-info"
}
if (cat == 'Warning') {
document.getElementById(ID).style.backgroundColor = '#fcf8e3'; //Orange Color
document.getElementById(PID).style.backgroundColor = '#fcf8e3'; //Orange Color
document.getElementById(PID).style.margin = '3px';
document.getElementById(BID).style.backgroundColor = '#fcf8e3';
document.getElementById(BID).style.border = 'none';
innerDiv.className = "alert alert-warning"
element.className = "alert alert-warning"
}
if (cat == 'Critical') {
document.getElementById(ID).style.backgroundColor = '#f2dede'; //Red Color
document.getElementById(PID).style.backgroundColor = '#f2dede'; //Red Color
document.getElementById(PID).style.margin = '3px';
document.getElementById(BID).style.backgroundColor = '#f2dede';
document.getElementById(BID).style.border = 'none';
innerDiv.className = "alert alert-danger"
element.className = "alert alert-danger"
}
}
// The below variables and for loop ensure that all sub messages are initially hidden, until the show/hide button is clicked
var curDiv
var curID
for (var i = 0; i < divCount; i++) {
curID = "P-" + i
curDiv = document.getElementById(curID)
curDiv.style.display = 'none';
}
// The function below is to assign an event to the button to show/hide the sub message
var f = function(a) {
var cDiv
for (var z = 0; z < divCount; z++) {
cDiv = "P-" + z
var div = document.getElementById(cDiv);
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
}
return false;
}
var elems = document.getElementsByClassName("toggle");
var idx
for (var i = 0, len = elems.length; i < len; i++) {
elems[i].onclick = f;
}
});
<div id="wrapper" class="header"> </div>
You're assigning all of your buttons the same onclick function event handler, and that function loops through all the divs and shows them or hides them.
An alternative approach would be to have the event handler toggle only the specific div that's associated with the button.
When you first create the button, you can assign an event handler to it immediately and pass in a reference to the div you want to hide:
var innerDiv = document.createElement("div");
innerDiv.id = PID
innerDiv.appendChild(document.createTextNode(message));
var btn = document.createElement("BUTTON");
// Immediately-invoked function expression to attach event handler to inner div:
(function(d){
btn.onclick = function(){ f(d); };
})(innerDiv);
Then just update your f function to accept as a parameter the div you want to toggle.
// The function below is to assign an event to the button to show/hide the sub message
function f(div){
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
return false;
}
You can then remove the last few lines of code where you're assigning the buttons to the elems collection and looping through it to attach an onclick function.
You can replace all of this - which loops over all divs
// The function below is to assign an event to the button to show/hide the sub message
var f = function(a) {
var cDiv
for (var z = 0; z < divCount; z++) {
cDiv = "P-" + z
var div = document.getElementById(cDiv);
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
}
return false;
}
var elems = document.getElementsByClassName("toggle");
var idx
for (var i = 0, len = elems.length; i < len; i++) {
elems[i].onclick = f;
}
with this, it delegates the click on the button in the wrapper and toggles the next object after the button
$('#wrapper').on("click",".toggle",function(e) { // notice the delegation
e.preventDefault(); // in case you forget type="button"
$(this).next().toggle();
});
Like this:
$(function() {
$('#wrapper').on("click", ".toggle", function(e) {
e.preventDefault();
$(this).next().toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="wrapper">
<div id="NewDiv-0" class="alert alert-info" style="background-color: rgb(217, 237, 247);">Debbie Teng joins PD Tax!********
<button id="btn-0" class="toggle" style="background-color: rgb(217, 237, 247); border: none;">show/hide message below</button>
<div id="P-0" class="alert alert-info" style="background-color: rgb(217, 237, 247); margin: 3px; display: none;">yadayada1​</div>
</div>
</div>

Javascript - onclick event is not working

So I have this piece of code:
window.onload = function () {make_buttons ('calc'); }
function make_buttons (id) {
console.log (id);
var input = document.createElement("INPUT");
document.getElementById(id).appendChild(input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("BUTTON");
var t = document.createTextNode (i);
btn.appendChild(t);
document.getElementById(id).appendChild(btn).onclick=document.getElementsByTagName("INPUT").value=i;
}
};
Now when I have created the button with the for loop, it should also have the onclick event attached to it which writes the current value of i into my input form.
Code I have written produces no errors but when the button is clicked, it simply does not do anything. Why is that?
New version:
window.onload = function () {make_buttons ('calc'); }
function make_buttons (id) {
var input = document.createElement("input");
input.type = 'text';
input.id = 'inp';
document.getElementById(id).appendChild(input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("button");
btn.id = i;
var txt = document.createTextNode (i);
btn.appendChild(txt);
var make_btn = document.getElementById(id).appendChild(btn);
make_btn.onclick = button_pressed (i);
}
};
function button_pressed (id) {
document.getElementById("inp").value += id;
};
Method document.getElementsByTagName() returns a NodeList collection that you should iterate through.
You need to go in loop through retrieved elements and assign the value attribute to each of them.
So that you can change
document.getElementById(id).appendChild(btn).onclick=document.getElementsByTagName("INPUT").value=i;
to something like this:
var id = 'my-form',
btn = document.createElement('input');
btn.type = 'button';
btn.value = 'Click me!';
btn.onclick = function() {
var inputs = document.getElementsByTagName('input');
// NodeList to Array if needed:
// var inputsArray = Array.prototype.slice.call(inputs);
for(var i = 0, l = inputs.length; i < l; i++) {
inputs[i].value = i;
}
return false;
};
document.getElementById(id).appendChild(btn);
DEMO #1
Update:
About your second question, yes it won't work in this way since at the time when your onclick event handler is called it's using the last value assigned to i variable. To avoid this you can just use closures.
For example,
HTML:
<form action="" id="my-form">
<input type="text" id="inp" />
</form>
JavaScript:
var btn,
input,
form,
createHandler;
input = document.getElementById('inp');
form = document.getElementById('my-form');
createHandler = function(i) {
return function() {
input.value += i;
};
};
for(var i = 0; i < 5; i++) {
btn = document.createElement('input');
btn.type = 'button';
btn.value = 'Append ' + i;
form.appendChild(btn);
btn.onclick = createHandler(i);
}
DEMO #2
Also you can use just immediately invoked anonymous function to create that closure in the body of your loop:
for(var i = 0; i < 5; i++) {
// ...
btn.onclick = (function(theNumberToAppend) {
return function() {
input.value += theNumberToAppend;
};
})(i);
}
DEMO #3

Categories

Resources