How to set Id to button created using Javascript? - 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.

Related

Remove input and buttons by button function

With a loop, I´m creating some inputs and buttons. One button is a remove button. If I press the remove button, I want to remove all inputs and buttons with that loop.
So e.g. if I press the third remove button, all of the created elements in the third loop run should be removed.
My function for that button isn´t working. Can someone help me out and tell/show me what I have to change in my code in order for it to work?
Thank you and Kind Regards
This is a part of my code:
for(var i = 0; i < arrayinput.length; i++){
// example input
var myParent1 = InputContainer;
var numberfield = document.createElement("input");
numberfield.setAttribute('class','InputNew');
numberfield.setAttribute('id','InputNew-' + i);
numberfield.setAttribute('value','0');
myParent1.appendChild(numberfield);
//example button
var myParent2 = AddContainer;
var addierenButton = document.createElement("button");
addierenButton.setAttribute('class','addButton');
addierenButton.textContent = "+";
addierenButton.id = "add_btn_" + i;
addierenButton.setAttribute('onclick','add(this)');
myParent.appendChild(addButton);
//remove button
var myParent3 = RemoveContainer;
var removeButton = document.createElement("button");
removeButton.setAttribute('class','removeButton');
removeButton.id = "remove_btn_" + i;
removeButton.textContent = "X";
removeButton.setAttribute('onclick','remove(this)');
myParent3.appendChild(removeButton);
};
function remove(btn){
const num = btn.id.replace("remove_btn_", "");
var delInput= document.getElementById("InputNew-" + num);
var delAdd= document.getElementById("add_btn_" + num);
var delRemove= document.getElementById("remove_btn_" + num);
delInput.remove();
delAdd.remove();
delRemove.remove();
};
The code logic is good but you had a few syntax errors.
Try the following snippet
const arrayinput = [0, 1, 2];
window.onload = (event) => {
for(var i = 0; i < arrayinput.length; i++){
// example input
var myParent1 = document.getElementById('root');
var numberfield = document.createElement("input");
numberfield.setAttribute('class','InputNew');
numberfield.setAttribute('id','InputNew-' + i);
numberfield.setAttribute('value','0');
myParent1.appendChild(numberfield);
//example button
var myParent2 = document.getElementById('root');
var addButton = document.createElement("button");
addButton.setAttribute('class','addButton');
addButton.textContent = "+";
addButton.id = "add_btn_" + i;
addButton.setAttribute('onclick','add(this)');
myParent2.appendChild(addButton);
//remove button
var myParent3 = document.getElementById('root');
var removeButton = document.createElement("button");
removeButton.setAttribute('class','removeButton');
removeButton.id = "remove_btn_" + i;
removeButton.textContent = "X";
removeButton.setAttribute('onclick','remove(this)');
myParent3.appendChild(removeButton);
}
}
function remove(btn){
const num = btn.id.replace("remove_btn_", "");
var delInput= document.getElementById("InputNew-" + num);
var delAdd= document.getElementById("add_btn_" + num);
var delRemove= document.getElementById("remove_btn_" + num);
delInput.remove();
delAdd.remove();
delRemove.remove();
}
<div id="root"></div>

How to assign a value to a new button

for (var i = 0; i < animals.length; i++) {
btn = $("<button>");
btn.attr("class", "btn");
btn.attr("value", animals[i]);
btn.text(celebrities[i]);
console.log(btn.value);
$("#animals").append(btn);
}
Console logging btn.value returns undefined. What am I doing wrong?
Button don't have value attribute, use can use data-value to set attribute for button like this. Also you wrong format btn = $("<button>");
btn = $("button");
btn.attr("class", "btn");
btn.attr("data-value", "Test Value");
btn.text("Text");
console.log(btn.text());
console.log(btn.data("value"));
btn = $("button");
btn.attr("class", "btn");
btn.attr("data-value", "Test Value");
btn.text("Text");
console.log(btn.text());
console.log(btn.data("value"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button></button>
If you want to do this is pure JS follow the below steps.
1) Create an element using the createElement function of the document. this function through you can create any king of HTML/OWN element
2) user setAttribute function for setting the attribute
3) Append element into the parent element of the document
var animals = ['tiger','dingo','panther']
var celebrities = ['cel1 1','cel 2','cel 3']
for (var i = 0; i < animals.length; i++) {
btn = document.createElement('button');
btn.setAttribute("class", "btn");
//btn.setAttribute("onclick","clickfunction");
btn.setAttribute("value", animals[i]);
btn.innderText = celebrities[i];
console.log(btn.value);
document.getElementById("animals").append(btn);
}

HTML & Javascript - Using a loop to create buttons doesn't "individualize" .onclick = {} [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 3 years ago.
I feel like this question has already been answered, but I couldn't find it, so I'll ask it anyways.
I was playing with Javascript in HTML, and I decided to make a whole bunch of buttons using a loop. I wanted to assign a function to each one based on which it was. Here, I'll show you the script:
for (var i = 0; i < 6; i++) {
var button = document.createElement("button");
button.innerHTML = i;
button.className = "buttonclass";
button.onclick = function() {alert(i)};
var buttonDiv = document.getElementById("buttons");
buttonDiv.appendChild(button);
}
But when I click on any of the buttons, it returns a "6". I know where the problem is; I can't use simply {alert(i)}. But what should I use instead?
If you are restricted to using var for browser support purposes, you can use functions to properly encapsulate some of these values so that the result isn't hoisted and set to the last value of i.
function generateButtons() {
var i;
var buttonDiv = document.getElementById("buttons");
for (var i = 0; i < 6; i++) {
generateButton(i, buttonDiv);
}
}
function generateButton(iteration, container) {
var button = document.createElement("button");
button.innerHTML = iteration;
button.className = "buttonclass";
button.onclick = function() { alert(iteration); }
container.appendChild(button);
}
generateButtons();
<div id="buttons"></div>
However, if you are able to use more modern containers like let and const, then you can keep the simpler structure and leverage the magic of block scoped containers:
for (let i = 0; i < 6; i++) {
let button = document.createElement("button");
button.innerHTML = i;
button.className = "buttonclass";
button.onclick = function() {alert(i)};
let buttonDiv = document.getElementById("buttons");
buttonDiv.appendChild(button);
}
<div id="buttons"></div>
The problem is that when you call alert(i), it is after the loop. After the loop, i is 6. You need to save the value of i, so you can call it later.
for (var i = 0; i < 6; i++) {
var button = document.createElement("button");
button.innerHTML = i;
button.className = "buttonclass";
var buttonDiv = document.getElementById("buttons");
buttonDiv.appendChild(button);
let a = i
button.onclick = function () { alert(a) };
}

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 to set button onclick event in for loop 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);
}

Categories