How to set button onclick event in for loop javascript - javascript

I'm trying to dynamically create a div for each user's campaign.
What I'd really like to see is a "show details" button inside the div that redirects to the campaign details. I tried to run this code, but it only takes the last index.
for (var i = utente.campagne.length - 1; i >= 0; i--) {
var appended = document.createElement("DIV");
appended.className = "jumbotron";
var nome = document.createElement("p");
nome.innerHTML = "Campaign Name: " + utente.campagne[i].nome;
appended.appendChild(nome);
var button = document.createElement("INPUT");
button.type = "button";
var index = i;
button.addEventListener('click', function () {
window.location = "ShowDetails.jsp?indexcampagna=" + index;
});
button.value = "show details";
button.className = "btn btn-primary btn-sm";
appended.appendChild(button);
var col = document.createElement("DIV");
col.className = "col-lg-4 col-sm-6 text-center";
col.appendChild(appended);
document.getElementById("boxes").appendChild(col);
}

Related

HTML Javascript dynamically add and remove textboxes

I'm trying to add and remove text boxes dynamically using javascript and HTML.
I can get it to add and remove but sometimes the remove button doesn't work. when I inspect the element it says that there is no onclick value for the remove button. I don't understand why when I set the onclick in the add function.
Heres my code:
<div id="reqs">
<h3 align = "center"> Requirements </h3>
<script>
var reqs_id = 0;
function removeElement(elementId,elementId2) {
// Removes an element from the document
var element2 = document.getElementById(elementId2);
var element = document.getElementById(elementId);
element2.parentNode.removeChild(element2);
element.parentNode.removeChild(element);
}
function add() {
reqs_id++;// increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class","w3-input w3-border");
input.setAttribute('id','reqs'+reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id','reqsr'+reqs_id);
remove.onclick = function() {removeElement('reqs'+reqs_id,'reqsr'+reqs_id);return false;};
remove.setAttribute("type","button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
This will work:
<div id="reqs">
<h3 align="center"> Requirements </h3>
</div>
<script>
var reqs_id = 0;
function removeElement(ev) {
var button = ev.target;
var field = button.previousSibling;
var div = button.parentElement;
div.removeChild(button);
div.removeChild(field);
}
function add() {
reqs_id++; // increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e)
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove" + reqs_id;
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
Fixed from my previous answer. Another option that may be necessary is to have each element know its exact place and be able to adjust itself based on what was added or removed. This enhancement will account for that by re-adjusting and ensuring your elements are always in order. (if desired)
See JSFiddle example.
Html
<div id="reqs">
<h3>Requirements</h3>
<button type="button" value="Add" onclick="javascript:add();">Add</button>
<br>
</div>
Javascript
function removeElement(e) {
let button = e.target;
let field = button.previousSibling;
let div = button.parentElement;
let br = button.nextSibling;
div.removeChild(button);
div.removeChild(field);
div.removeChild(br);
let allElements = document.getElementById("reqs");
let inputs = allElements.getElementsByTagName("input");
for(i=0;i<inputs.length;i++){
inputs[i].setAttribute('id', 'reqs' + (i+1));
inputs[i].setAttribute('value', (i+1));
inputs[i].nextSibling.setAttribute('id', 'reqsr' + (i+1));
}
}
function add() {
let allElements = document.getElementById("reqs");
let reqs_id = allElements.getElementsByTagName("input").length;
reqs_id++;
//create textbox
let input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
let reqs = document.getElementById("reqs");
//create remove button
let remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e);
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
let br = document.createElement("br");
reqs.appendChild(br);
}

how do i add functionality to each of the buttons?

The first part of the code is working correctly, but now that each button appears, how do i add functionality to each of them? currently the only button which does something when pressed is always the last one, the rest do nothing.
Change it to
{
var output = "";
var data = JSON.parse(e.target.responseText);
for(var i=0; i<data.length; i++)
{
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
p.appendChild(button);
div.appendChild(p);
button.addEventListener ("click", () =>
{
alert("Test");
});
}
}
You are adding the below code out side the for loop
button.addEventListener ("click", () =>
{
alert("Test");
} );
Keep the above code inside the for loop. So that for each button the event listener will be added.
Another way to approach this would be to add the callback function to the onclick variable of the elements prototype:
function doStuff() {
var output = "";
var data = JSON.parse(e.target.responseText);
for (var i = 0; i < data.length; i++) {
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
// Adds the callback function here
button.onclick = () => {
// fill in your arrow function here...
alert("Test");
};
p.appendChild(button);
div.appendChild(p);
};
}
doStuff();
Here is a jsFiddle
You should use event delegation for dynamically added elements
// sample data
var data = [{
title: 'one'
}, {
title: 'two'
},{
title: 'three'
}];
var output = "";
for (var i = 0; i < data.length; i++) {
var output = data[i].title + " ";
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
// added output to button text for identification
button.innerHTML = output + " Download";
p.appendChild(button);
div.appendChild(p);
}
// Get the parent element, add a click listener
document.getElementById("response").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a button
if (e.target && e.target.nodeName == "BUTTON") {
// Button found! Output the identifying data!
// do other work on click
document.getElementById("display").innerHTML = e.target.innerHTML + " Clicked";
}
});
<div id="response"></div>
<div id="display">Display</div>

Swap heading with button text

I'm working on a challenge that requires I only use Javascript (no jQuery). I created an HTML with twelve different buttons and an heading at the bottom. I want to switch the heading with the buttons text on click but mostly receive the error "Uncaught TypeError: Cannot set property 'innerHTML' of null/undefined."
I included the whole script, and I know my createHTML function could use some cleaning up, but I only included it so you can see how I added the click handler. switchHeading function is at the bottom.
function createHTML(){
var container = document.getElementsByClassName("container");
//add div "row"
var row = document.createElement("div");
row.className = "row";
container[0].appendChild(row);
//add div "col"
var col = document.createElement("div");
col.className = "col-md-12";
row.appendChild(col);
//add star button
var starButton = document.createElement("button");
starButton.className = "btn btn-default btn-lg";
starButton.setAttribute("type", "button");
starButton.onclick = switchHeading();
col.appendChild(starButton);
starButton.appendChild(document.createTextNode("Star"));
//add hr
var hr = document.createElement("hr");
col.appendChild(hr);
//add div
var div = document.createElement("div");
col.appendChild(div);
//add btn group
var btnGroup = document.createElement("div");
btnGroup.className = "btn-group";
div.appendChild(btnGroup);
//add num btns
for(var i=1; i<5; i++){
var numButton = document.createElement("button");
numButton.className="btn btn-default";
numButton.setAttribute("type", "button");
numButton.onclick = switchHeading();
btnGroup.appendChild(numButton);
numButton.appendChild(document.createTextNode(i));
}
//add btn group2
var btnGroup2 = document.createElement("div");
btnGroup2.className = "btn-group";
div.appendChild(btnGroup2);
//add some more num buttons
for(var i=5; i<8; i++){
var numButton = document.createElement("button");
numButton.className="btn btn-default";
numButton.setAttribute("type", "button");
numButton.onclick = switchHeading();
btnGroup2.appendChild(numButton);
numButton.appendChild(document.createTextNode(i));
}
//add 8 button
var btnGroup3 = document.createElement("div");
btnGroup3.className ="btn-group";
div.appendChild(btnGroup3);
var ochoButton = document.createElement("button");
ochoButton.className = "btn btn-default";
ochoButton.setAttribute("type", "button");
ochoButton.onclick = switchHeading();
btnGroup3.appendChild(ochoButton);
ochoButton.appendChild(document.createTextNode(8));
//2nd hr
var hr2 = document.createElement("hr");
col.appendChild(hr2);
//Anotha div
var anotherDiv = document.createElement("div");
col.appendChild(anotherDiv);
//last btn group
var btnGroupLg = document.createElement("div");
btnGroupLg.className = "btn-group btn-group-lg";
anotherDiv.appendChild(btnGroupLg);
//LMR buttons
var LButton = document.createElement("button");
LButton.className = "btn btn-default";
LButton.setAttribute("type", "button");
LButton.onclick = switchHeading();
btnGroupLg.appendChild(LButton);
LButton.appendChild(document.createTextNode("Left"));
var MButton = document.createElement("button");
MButton.className = "btn btn-default";
MButton.setAttribute("type", "button");
MButton.onclick = switchHeading();
btnGroupLg.appendChild(MButton);
MButton.appendChild(document.createTextNode("Middle"));
var RButton = document.createElement("button");
RButton.className = "btn btn-default";
RButton.setAttribute("type", "button");
RButton.onclick = switchHeading();
btnGroupLg.appendChild(RButton);
RButton.appendChild(document.createTextNode("Right"));
//add h3
var h3 = document.createElement("h3");
h3.id = "heading";
anotherDiv.appendChild(h3);
h3.appendChild(document.createTextNode("Click a Button!"));
};
createHTML();
function switchHeading() {
var content = this.innerHTML;
var h3 = document.getElementsByTagName('h3');
h3[0].innerHTML = content;
}
Make sure you've got h3 tag on your page and get rid of parentheses in
RButton.onclick = switchHeading();
The parentheses make function switchHeading() run immediately wich leads to undefined result since switchHeading() has no return value. This works:
<html>
<div class="container"></div>
<h3>Hello</h3>
<script>
function createHTML(){
var container = document.getElementsByClassName("container");
//add div "row"
var row = document.createElement("div");
row.className = "row";
container[0].appendChild(row);
//add div "col"
var col = document.createElement("div");
col.className = "col-md-12";
row.appendChild(col);
//add star button
var starButton = document.createElement("button");
starButton.className = "btn btn-default btn-lg";
starButton.setAttribute("type", "button");
starButton.onclick = switchHeading;
col.appendChild(starButton);
starButton.appendChild(document.createTextNode("Star"));
//add hr
var hr = document.createElement("hr");
col.appendChild(hr);
//add div
var div = document.createElement("div");
col.appendChild(div);
//add btn group
var btnGroup = document.createElement("div");
btnGroup.className = "btn-group";
div.appendChild(btnGroup);
//add num btns
for(var i=1; i<5; i++){
var numButton = document.createElement("button");
numButton.className="btn btn-default";
numButton.setAttribute("type", "button");
numButton.onclick = switchHeading;
btnGroup.appendChild(numButton);
numButton.appendChild(document.createTextNode(i));
}
//add btn group2
var btnGroup2 = document.createElement("div");
btnGroup2.className = "btn-group";
div.appendChild(btnGroup2);
//add some more num buttons
for(var i=5; i<8; i++){
var numButton = document.createElement("button");
numButton.className="btn btn-default";
numButton.setAttribute("type", "button");
numButton.onclick = switchHeading;
btnGroup2.appendChild(numButton);
numButton.appendChild(document.createTextNode(i));
}
//add 8 button
var btnGroup3 = document.createElement("div");
btnGroup3.className ="btn-group";
div.appendChild(btnGroup3);
var ochoButton = document.createElement("button");
ochoButton.className = "btn btn-default";
ochoButton.setAttribute("type", "button");
ochoButton.onclick = switchHeading;
btnGroup3.appendChild(ochoButton);
ochoButton.appendChild(document.createTextNode(8));
//2nd hr
var hr2 = document.createElement("hr");
col.appendChild(hr2);
//Anotha div
var anotherDiv = document.createElement("div");
col.appendChild(anotherDiv);
//last btn group
var btnGroupLg = document.createElement("div");
btnGroupLg.className = "btn-group btn-group-lg";
anotherDiv.appendChild(btnGroupLg);
//LMR buttons
var LButton = document.createElement("button");
LButton.className = "btn btn-default";
LButton.setAttribute("type", "button");
LButton.onclick = switchHeading;
btnGroupLg.appendChild(LButton);
LButton.appendChild(document.createTextNode("Left"));
var MButton = document.createElement("button");
MButton.className = "btn btn-default";
MButton.setAttribute("type", "button");
MButton.onclick = switchHeading;
btnGroupLg.appendChild(MButton);
MButton.appendChild(document.createTextNode("Middle"));
var RButton = document.createElement("button");
RButton.className = "btn btn-default";
RButton.setAttribute("type", "button");
RButton.onclick = switchHeading;
btnGroupLg.appendChild(RButton);
RButton.appendChild(document.createTextNode("Right"));
//add h3
var h3 = document.createElement("h3");
h3.id = "heading";
anotherDiv.appendChild(h3);
h3.appendChild(document.createTextNode("Click a Button!"));
};
createHTML();
function switchHeading() {
var content = this.innerHTML;
var h3 = document.getElementsByTagName('h3');
h3[0].innerHTML = content;
}
</script>
</html>

How to set Id to button created using Javascript?

// how to set id to this created buttons?
for(i=1;i<=3;i++)
{
var btn = document.createElement("BUTTON");// create button using java script
btn.className = "btnsize";
var txt = document.createTextNode(num++);//creat text on button
btn.appendChild(txt);//attached text on button
document.getElementById("xyz").appendChild(btn);//atache button with text in div
}
for (i = 1; i <= 3; i++) {
var btn = document.createElement("BUTTON");
btn.setAttribute("class","btnsize");
btn.setAttribute("id","btnid"+i);
var txt = document.createTextNode("button");
btn.appendChild(txt);
document.getElementById("xyz").appendChild(btn);
}
btn.id = "btnid"+i
This will number them accordingly
html
<div id="xyz"></div>
js
for (i = 1; i <= 3; i++) {
var btn = document.createElement("BUTTON");// create button using java script
btn.className = "btnsize";
btn.id = "btnid"+ i;
var txt = document.createTextNode("aaasasa");//creat text on button
btn.appendChild(txt);//attached text on button
document.getElementById("xyz").appendChild(btn);//atache button with text in div
}
DEMO
In you code num is not defined. you should add i in btn.id = "btnid"+ i; for unique ids.

Removing the corresponding textbox of the anchor tag

I have created a simple application in javascript. The application is that a value is selected from a dropdown list and if the button next to it is clicked then the specified number of texboxes selected in the dropdown are added to the DOM with a a to their right sides.
Here's the HTML:
<form>
<select style="width: 250px;" id="numMembers" <!--onchange="addMembers();" -->>
<option value="0">Add More Members...</option>
<script>
for (var i = 1; i <= 10; i++) {
document.write('<option value=' + i + '>' + i + '</option>');
};
</script>
</select>
<button onclick="addMembers();" type="button">Add</button>
<div style="margin-top: 10px; border: 1px solid #eee; padding: 10px;">
<input type="text" />
<br/>
<input type="text" />
<br/>
<input type="text" />
<br/>
</div>
<div id="extras"></div>
</form>
And here's the script:
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function () {
document.removeChild(this);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
How can I remove the textbox on the left of the anchor tag which is when clicked. For example:
[XXXXXXX] Remove(x)
[XXXXXXX] Remove(x)
If the last "Remove(x)" is clicked then the last textbox should be removed hence the one to the left of it.
How can I do it?
Note: No JQuery solutions please! I could do that even myself :P.
You can pass the id on anchorTag and can pass same id with some addition for input text, like
If you pass the id input1 for a then use the id input1Text for relative text box,
So you when you click on particular link, you will get a with input1 and get relative input text with 'input1Text'.
This would be apply for input2, input3, ... Something like this.
DEMO
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.type = "text";
txtInput.id = "input"+i+"Text"; //give the id with Text
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
//when you click on this link you will get relative textbox by "input"+i+"Text";
removeHref.id = "input"+i;
removeHref.onclick = function () {
var removeNodeText = document.getElementById(this.id+"Text");
removeNodeText.parentNode.removeChild(removeNodeText);
var removeNodeLink = document.getElementById(this.id);
removeNodeLink.parentNode.removeChild(removeNodeLink);
};
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}
Try This
function addMembers() {
var num = document.getElementById("numMembers").options["selectedIndex"];
for (var i = 0; i < num; i++) {
var lineBreak = document.createElement("br")
var txtInput = document.createElement("input");
txtInput.id = "text_"+i;
txtInput.type = "text";
txtInput.style.display = "inline";
var removeHref = document.createElement("a");
removeHref.href = "#";
removeHref.id = "href_"+i;
removeHref.innerHTML = "Remove(x)";
removeHref.style.marginLeft = "5px";
removeHref.style.display = "inline";
removeHref.onclick = function(){
var id= this.id.split('_')[1];
console.log(id)
document.getElementById("extras").removeChild(document.getElementById('text_'+id));
document.getElementById("extras").removeChild(this);
}
document.getElementById("extras").appendChild(lineBreak);
document.getElementById("extras").appendChild(txtInput);
document.getElementById("extras").appendChild(removeHref);
}
}

Categories