How to append more than one element using appendChild - javascript

I have one cell (columns), in which I want to add two buttons. This is what I created:
var editbtn = document.createElement('button');
editbtn.type= "button";
editbtn.className= "editbtn";
editbtn.id= "edit-button-"+(i+1);
editbtn.innerHTML= "Edit";
editbtn.onclick = editRow.bind(this, i + 1);
var savebtn = document.createElement('button');
savebtn.type= "button";
savebtn.className= "savebtn";
savebtn.id= "save-button-"+(i+1);
savebtn.innerHTML= "Save";
savebtn.onclick = saveRow.bind(this, i + 1);
cell3.appendChild(editbtn);
cell3.appendChild(savebtn);
However, only the savebtn appears. How to append two buttons or more in the same column?

You can easily do that with an array and a for loop:
var names = ['edit', 'save'];
var editRows = [editRow, saveRow];
for ( var i = 0; i < names.length; i++ )
{
var btn = document.createElement('button');
btn.type = "button";
btn.className = names[i] + "btn";
btn.id = names[i] + "-button-" + (i+1);
btn.innerHTML = names[i];
btn.onclick = editRows[i].(this, i + 1);
cell3.appendChild( editbtn );
}
You can add as many button as you want then just updating names and editRows accordingly, no need to touch the for loop.

Related

Why only last nested element is visible - javascript using appendChild()?

I am trying dynamically add fields on button click and have several nested elements but only last nested element is visible.
var i = 1;
function add_new_recipient() {
var div_group = document.createElement("div");
div_group.setAttribute("class", "input-group");
var input = document.createElement("INPUT");
input.setAttribute("id", "txt_recipients" + i);
input.setAttribute("Name", "txt_recipients" + i);
input.setAttribute("type", "text");
input.setAttribute("class", "form-control required txt_recipients");
input.setAttribute("runat", "server");
var span = document.createElement("span");
span.setAttribute("class", "input-group-append");
var button_add = document.createElement("button");
button_add.setAttribute("id", "btn_add_new_recipients_field" + i);
button_add.setAttribute("type", "button");
button_add.setAttribute("class", "btn btn-primary btn_add_new_recipients_field fa fa-plus");
button_add.onclick = function () {
add_new_recipient();
}
var button_remove = document.createElement("button");
button_remove.setAttribute("id", "btn_remove_new_recipients_field" + i);
button_remove.setAttribute("type", "button");
button_remove.setAttribute("class", "btn btn-primary btn_remove_new_recipients_field fa fa-minus");
button_remove.onclick = function () {
remove_recipient();
}
span.appendChild(button_add);
span.appendChild(button_remove);
input.appendChild(span);
div_group.append(input);
document.getElementById("new_recipient_input").appendChild(div_group);
i++;
}
Only Input field is visible but not buttons.

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 do you print out the index of a list element in an ordered list?

I have this code that on a button click, it spawns a group of elements inside a list. each of this groups is indexed in the ordered list in ascending order 1,2,3 etc.. i need these numbers to be stored for use in my database.
currently I haven't been able to find a way to identify the index number of each group in the list and thus add them as attributes.
This is my JS for spawning a group:
function spawnSilly() //spawn chapters function
{
var div = document.createElement("LI");
var input = document.createElement("INPUT");
var button = document.createElement("BUTTON");
var del_button = document.createElement("BUTTON")
input.setAttribute("type", "text");
input.setAttribute("placeholder", "Title");
input.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.setAttribute("type", "button");
button.setAttribute("onClick", "redirect()");
button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.innerHTML = "Edit";
div.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.innerHTML = "Delete";
del_button.setAttribute("onClick", "removeElement(this.id)")
div.appendChild(input)
div.appendChild(button)
div.appendChild(del_button);
var list = document.getElementById("spawnList");
list.insertBefore(div, list.childNodes[0]);
set_index();
}
I've been using this JS code to add an index, but I cannot tell if it's working as I cant print out the index of a spawned list element.
function set_index()
{
var ol = document.getElementById('spawnList');
// select the list items
var lists = ol.getElementsByTagName('li');
var l = lists.length; // total items
//custom list id's via loop
for (var i=1;i<=l;i++)
{
list[i].index = i;
}
}
This is my HTML:
<ol id="spawnList">
</ol>
<button id="spawnbtn" onClick="spawnSilly(); ">Add</button>
This is really bugging me, any help would be fantastic! Thanks :)
I change way to add li tag in ol tag and it show index.
var list = document.getElementById("spawnList");
list.appendChild(div);
var index = 1;
function spawnSilly() //spawn chapters function
{
var div = document.createElement("LI");
var input = document.createElement("INPUT");
var button = document.createElement("BUTTON");
var del_button = document.createElement("BUTTON")
input.setAttribute("type", "text");
input.setAttribute("placeholder", "Title");
input.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.setAttribute("type", "button");
button.setAttribute("onClick", "redirect()");
button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
button.innerHTML = "Edit";
div.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.setAttribute("id", "var timestamp = new Date().getUTCMilliseconds();")
del_button.innerHTML = "Delete";
del_button.setAttribute("onClick", "removeElement(this.id)")
div.appendChild(input)
div.appendChild(button)
div.appendChild(del_button);
var list = document.getElementById("spawnList");
//var li = document.createElement("li");
list.appendChild(div);
console.log(index++);
//list.insertBefore(div, list.childNodes[0]);
//set_index();
}
function set_index()
{
var ol = document.getElementById('spawnList');
// select the list items
var lists = ol.getElementsByTagName('li');
if(lists != undefined){
var l = lists.length; // total items
//custom list id's via loop
for (var i=1;i<=l;i++)
{
list[i].index = i;
}
}
}
<ol id="spawnList">
</ol>
<button id="spawnbtn" onClick="spawnSilly(); ">Add</button>

document.getElementById class applies to the whole array instead of each element

<p><span id="sr" class="btn">elements of the array</span></p>
for(var i = 0; i < myarray.length; i++)
{
var sr = (function(val) {
btn = document.createElement('button');
btn.data = val;
btn.innerHTML = val;
btn.addEventListener('click', checkAnswer);
document.body.appendChild(btn);
return btn.data = val;
})//(myarray[i]);
document.getElementById("sr").innerHTML = myarray;
}
With this code the elements of the array appear in the html span. I want each element to appear as a button, as defined in the class "btn". However, the class changes the style of the array as a whole, not as single buttons. What is the correct way to define the style of each button?
I tried document.getElementById("sr").innerHTML = myarray.class="btn";. It does not work. Definitely not the correct syntax. Any idea?
Is this what you want to achieve?
let container = document.getElementById('sr');
let array = ['element1', 'element2', 'element3'];
function checkAnswer () {
console.log('Selected answer: ', this.textContent);
}
for (let i = 0; i < array.length; i++) {
let button = document.createElement('button');
button.textContent = array[i];
button.addEventListener('click', checkAnswer);
container.appendChild(button);
}
<p><span id="sr" class="btn"></span></p>
If I understand you correctly, you want to add btn class to your dynamically created buttons with myarray elements.
What is the correct way to define the style of each button?
I tried document.getElementById("sr").innerHTML = myarray.class="btn";
You can use element.classList.add('your-class');
var myarray = ["Array", "elements"]; //let's say
for (var i = 0; i < myarray.length; i++) {
var sr = (function(val) {
btn = document.createElement('button');
btn.data = val;
btn.innerHTML = val;
btn.classList.add("btn")
btn.addEventListener('click', checkAnswer);
document.body.appendChild(btn);
return btn.data = val;
})(myarray[i]);
//document.getElementById("sr").innerHTML = myarray;//I don't know why this line here?
}
function checkAnswer(e){
}
Use Element.dataset instead of creating a .data property. Pass i to IIFE. If you are trying to display the array myarray as .innerHTML of #sr, concatenate "[" to beginning and "]" to end of myarray setting at .innerHTML, as .innerHTML casts Array to String.
If you are trying to append created element to #sr, do not append element to document.body, but #sr.
function checkAnswer() {
console.log(this.dataset.value)
}
var myarray = [1, 2, 3];
for (var i = 0; i < myarray.length; i++) {
(function(val) {
var btn = document.createElement('button');
btn.dataset.value = val;
btn.className = "btn"; // set `btn` `.className` to `"btn"`
btn.innerHTML = val;
btn.addEventListener('click', checkAnswer);
document.body.appendChild(btn);
// document.getElementById("sr").appendChild(btn);
})(i);
}
document.getElementById("sr").innerHTML = "[" + myarray + "]";
<p><span id="sr" class="btn">elements of the array</span></p>

Replace header text with button text using JavaScript

I am using only JavaScript to create buttons and need to add click handlers to the buttons that will replace the header with the contents of the buttons. I have been trying to figure out how to do this for a while. Any help would be great! Thank you!
Below is my JavaScript code that creates the buttons and header.
var col = document.createElement('div');
col.className = 'col';
document.body.appendChild(col);
var header = document.getElementById('col');
var h = document.createElement("H3");
h.innerHTML = "Nothing clicked yet!";
col.appendChild(h);
var divOne = document.createElement('div');
col.appendChild(divOne);
var btnOne = document.getElementById('col');
var textOne = ["1", "2", "3", "4"];
textOne.forEach(function(post) {
var postDiv = document.createElement("div");
postDiv.className = 'btn btn-default';
postDiv.innerHTML = post;
col.appendChild(postDiv);
});
Add an event to your button elements, but as other answers pointed out, a good practice is to assign IDs to your elements for more accurate lookup :
var btnOne = document.getElementById('col');
var textOne = ["Left", "Middle", "Right"];
textOne.forEach(function(post) {
var btnGroupFour = document.createElement('button');
btnGroupFour.className = 'btn btn-default';
btnGroupFour.innerHTML = post;
btnGroupFour.addEventListener("click", function() {
var header = document.getElementsByTagName('H3')[0];
header.innerHTML = this.innerHTML;
}, false);
divThree.appendChild(btnGroupFour);
});
First of all, you are not creating buttons, you're creating divs, although you're using the button classes from bootstrap (I gues...).
Anyway, the way to proceed would be to add a onclick attribute with a callback function, witch takes one argument: the event itself. Then, with the target attribute of the event object, you're getting access to the event source tag and with value you will get the value.
Just like this:
<input type="button" id="button" value="Test Value!" />
<span id="output"></span>
<script>
document.getElementById("button").addEventListener('click', callback);
function callback(e) { document.getElementById("output").innerHTML = e.target.value; }
</script>
Just assign an ID for your header, and while creating the buttons in the loop. Just assign the onclick callback of the button, to get the id of the header, and replace the text
textOne.forEach(function(post) {
var btnGroupFour = document.createElement('button');
btnGroupFour.className = 'btn btn-default';
btnGroupFour.innerHTML = post;
btnGroupFour.onclick = function(){document.getElementById('headerID').innerHTML = post} ;
h.appendChild(btnGroupFour);
});
Should Work for your situation.
A short Demo
Fairly simple, just add an eventListener onto the element during creation. All I really had to add to your code was: .addEventListener("click", function(){ h.innerHTML = post;});
http://www.w3schools.com/jsref/met_element_addeventlistener.asp
<!DOCTYPE html>
<html>
<body>
<p>Hover over the checkbox to simulate a mouse-click.</p>
<script>
var divContainer = document.createElement('div');
divContainer.className = 'container';
document.body.appendChild(divContainer);
var row = document.createElement('div');
row.className = 'row';
divContainer.appendChild(row);
var col = document.createElement('div');
col.id = 'col-md-12';
row.appendChild(col);
var header = document.getElementById('col');
var h = document.createElement("H3");
h.innerHTML = "Nothing clicked yet!";
col.appendChild(h);
var star = document.createElement('div');
col.appendChild(star);
var btnStar = document.getElementById('col');
var textStar = ["Star"];
textStar.forEach(function(post) {
var postStar = document.createElement("div");
postStar.className = 'btn btn-default';
postStar.innerHTML = post;
postStar.addEventListener("click", function(){
h.innerHTML = post;});
col.appendChild(postStar);
});
var secondLine = document.createElement("HR");
document.body.appendChild(secondLine);
col.appendChild(secondLine);
var divOne = document.createElement('div');
col.appendChild(divOne);
var btnOne = document.getElementById('col');
var textOne = ["1", "2", "3", "4"];
textOne.forEach(function(post) {
var postDiv = document.createElement("div");
postDiv.className = 'btn btn-default';
postDiv.innerHTML = post;
postDiv.addEventListener("click", function(){
h.innerHTML = post;});
col.appendChild(postDiv);
});
var btnTwo = document.getElementById('col');
var textTwo = ["5", "6", "7", "8"];
textTwo.forEach(function(post) {
var btnGroupFour = document.createElement('button');
btnGroupFour.className = 'btn btn-default';
btnGroupFour.innerHTML = post;
btnGroupFour.addEventListener("click", function(){
h.innerHTML = post;});
col.appendChild(btnGroupFour);
});
var secondLine = document.createElement("HR");
document.body.appendChild(secondLine);
col.appendChild(secondLine);
var divThree = document.createElement('div');
col.appendChild(divThree);
var btnOne = document.getElementById('col');
var textOne = ["Left", "Middle", "Right"];
textOne.forEach(function(post) {
var btnGroupFour = document.createElement('button');
btnGroupFour.className = 'btn btn-default';
btnGroupFour.innerHTML = post;
btnGroupFour.addEventListener("click", function(){
h.innerHTML = post;});
divThree.appendChild(btnGroupFour);
});
</script>
</body>
</html>

Categories

Resources