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>
Related
I am trying to change the css property of the "node"-class by clicking on the div inside of it which got the class "expand".
When I click on the "expand" div inside the "note", I want to go to parent "note" for changing it size:
var text = document.getElementById("text");
var add = document.getElementById("add");
var notespace = document.getElementById("notespace");
var expand = document.getElementsByClassName("expand");
var notes = document.getElementsByClassName("note");
add.addEventListener("click", function () {
var textValue = text.value;
var p = document.createElement("p");
p.innerHTML = "<div class='note'>" + textValue +
"<br/><br/><div class='expand'> Expand </div></div>";
notespace.appendChild(p);
text.value = "";
for (var i = 0; i < expand.length; i++) {
expand[i].addEventListener("click", function () {
notes[i].style.size = "3000px";
})
}
})
You have to re-get the values of expand and notes, because after you add them to your html, the two variables expand and notes, dont know yet that you have added them and they don't contain them. ( you also have to removee the eventlistner otherwise you're gonna get a bugg at approximately twelve notes added :D because you will have too many eventListners on each element
var text = document.getElementById("text");
var add = document.getElementById("add");
var notespace = document.getElementById("notespace");
var expand = document.getElementsByClassName("expand");
var notes = document.getElementsByClassName("note");
add.addEventListener("click", function(){
var textValue = text.value;
var p = document.createElement("p");
p.innerHTML = "<div class='note'>" + textValue + "<br/><br/><div class='expand'> Expand </div></div>";
notespace.appendChild(p);
text.value = "";
for( var i = 0; i < expand.length; i++){
const note = notes[i];
expand[i].addEventListener("click", function() {
note.style.size = "3000px";
note.style.backgroundColor = "red";
});
}
})
#notespace {
width: 100%,
height: 100%,
background: grey,
}
<button type="button" id="add">add</button>
<input id="text"/>
<div id="notespace">
</div>
You can use the parentNode attribute :
for( var i = 0; i < expand.length; i++){
expand[i].addEventListener("click", function(){
this.parentNode.style.size = "3000px";
})
}
Or the closest() method :
for( var i = 0; i < expand.length; i++){
expand[i].addEventListener("click", function(){
this.closest(".note").style.size = "3000px";
})
}
Note that closest() is not supported on IE.
I need to exit from mine.onclick = function so can anyone help me??
I'm new in js!
I tried to write the word game and I need to write the function, when I'm clicking on the button I need to move the button, but its not working 3th time
//creating div
var div = document.createElement('div');
div.innerHtml = '';
document.body.appendChild(div);
div.classList.add('main');
//creating divsec
var divsec = document.createElement('div');
divsec.innerHtml = '';
document.body.appendChild(divsec);
divsec.classList.add('submain');
//creating array for words
var arr = prompt("Write your word or sentance here and don't accept your apponent to see that!");
array = arr.split('');
array = array.sort();
console.log(array);
alert("Let's construct the word!");
var main = document.getElementsByClassName('main');
var divsec = document.getElementsByClassName('submain');
for(var i = 0; i < arr.length; i++){
var button = document.createElement('button');
divsec[0].appendChild(button);
button.innerHTML = array[i];
button.onclick = function(){
mainp = main[0].appendChild(this);
mainp.onclick = function (){
divsec[0].appendChild(this);
}
}
}
Is this the answer you're looking for?
//creating div
var div = document.createElement('div');
div.innerHtml = '';
document.body.appendChild(div);
div.classList.add('main');
//creating divsec
var divsec = document.createElement('div');
divsec.innerHtml = '';
document.body.appendChild(divsec);
divsec.classList.add('submain');
//creating array for words
var arr = prompt("Write your word or sentance here and don't accept your apponent to see that!");
array = arr.split('');
array = array.sort();
console.log(array);
alert("Let's construct the word!");
var main = document.getElementsByClassName('main');
var divsec = document.getElementsByClassName('submain');
for(var i = 0; i < arr.length; i++){
var button = document.createElement('button');
divsec[0].appendChild(button);
button.innerHTML = array[i];
button.onclick = function(){
if (this.parentNode.className === 'main') divsec[0].appendChild(this)
else main[0].appendChild(this);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>
If it's not, please clarify your question and give an example of what is the desired effect on clicking a single button. I'm also not sure what you mean by exit the function. It seemed fine to me.
You stated that you need a button to move, but you didn't state how does it need to move.
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>
I am creating something with JS and I cannot seem to add the style tag to a div that I created via javascript (I am not making a class for css for a reason do not suggest it) here is my code
function createForm()
{
var container = document.getElementsByClassName("container-fluid");
var formElement = document.createElement("form");
var inputName = document.createElement("input");
var inputEvent = document.createElement("input");
var inputTime = document.createElement("input");
var sendWithTimer = document.createElement("input");
var sendWithoutTimer = document.createElement("input");
var divContainer = document.createElement("div");
formElement.className = "form";
divContainer.className = "enforce-styles";
inputName.className = "name";
inputEvent.className = "event";
inputTime.className = "time";
sendWithTimer.className = "sendWithTimer";
sendWithoutTimer.className = "sendWithoutTimer";
inputName.setAttribute('type', "text");
inputEvent.setAttribute('type', "text");
inputTime.setAttribute('type', "text");
inputName.setAttribute('placeholder', "Name");
inputEvent.setAttribute('placeholder', "Event");
inputTime.setAttribute('placeholder', "Time");
sendWithTimer.setAttribute('type', "button");
sendWithoutTimer.setAttribute('type', "button");
sendWithTimer.setAttribute('value', "Timer");
sendWithoutTimer.setAttribute('value', "No timer");
formElement.appendChild(inputName);
formElement.appendChild(inputEvent);
formElement.appendChild(inputTime);
divContainer.appendChild(sendWithTimer);
divContainer.appendChild(sendWithoutTimer);
for (var formElementStyles = 0; formElementStyles < formElement.length; formElementStyles++)
{
formElement[formElementStyles].style.display = "-webkit-flex";
formElement[formElementStyles].style.display = "flex";
formElement[formElementStyles].style.webkitFlexDirection = "column";
formElement[formElementStyles].style.flexDirection = "column";
formElement[formElementStyles].style.position = "relative";
formElement[formElementStyles].style.top = 0;
formElement[formElementStyles].style.left = 40 + "%";
formElement[formElementStyles].style.padding = 0.6 + "em";
formElement[formElementStyles].style.margin = 1 + "em";
}
for (var divContainerStyles = 0; divContainerStyles < divContainer.length; divContainerStyles++)
{
divContainer[divContainerStyles].style.display = "-webkit-flex";
divContainer[divContainerStyles].style.display = "flex";
divContainer[divContainerStyles].style.webkitFlexDirection = "column";
divContainer[divContainerStyles].style.flexDirection = "column";
divContainer[divContainerStyles].style.position = "relative";
divContainer[divContainerStyles].style.top = 0;
divContainer[divContainerStyles].style.left = 40 + "%";
divContainer[divContainerStyles].style.padding = 0.6 + "em";
divContainer[divContainerStyles].style.margin = 1 + "em";
divContainer[divContainerStyles].style.height = 10 + "em";
}
container[0].appendChild(formElement);
container[0].appendChild(divContainer);
}
I cannot seem to get the second for loop to place the style tags. The div just appears with nothing but a class name which was set above. But I cannot get the styles on there. The styles are for two buttons inside a form I am inserting into a clients website. How can I get this to work? What am I doing wrong?
Your code does not apply the style to the input fields, because divContainer.length does not exist, neither does divContainer[divContainerStyles]. divContainer is an div Object and has no length attribute (as opposed to the form element, which does have a length attribute) so that's why it never gets into the second loop.
Your code produces the following error: https://jsfiddle.net/tdbju0ud/
Instead, you should check for the length of divContainer.childNodes and apply the styles to those.
for (var divContainerStyles = 0; divContainerStyles < divContainer.childNodes.length; divContainerStyles++)
{
divContainer.childNodes[divContainerStyles].style.display = "-webkit-flex";
...
}
A working test in: https://jsfiddle.net/Lvq6hvxd/
This will work- divContainer[divContainerStyles].setAttribute('style', <your styles>)
Use childNodes to get the child elements of the div container.
like
var nodes = divContainer.childNodes
Find out the length of this nodes array object to find out the child elements count of the div.
Here is the corrected code :
var container = document.getElementsByClassName("container-fluid");
var formElement = document.createElement("form");
var inputName = document.createElement("input");
var inputEvent = document.createElement("input");
var inputTime = document.createElement("input");
var sendWithTimer = document.createElement("input");
var sendWithoutTimer = document.createElement("input");
var divContainer = document.createElement("div");
formElement.className = "form";
divContainer.className = "enforce-styles";
inputName.className = "name";
inputEvent.className = "event";
inputTime.className = "time";
sendWithTimer.className = "sendWithTimer";
sendWithoutTimer.className = "sendWithoutTimer";
inputName.setAttribute('type', "text");
inputEvent.setAttribute('type', "text");
inputTime.setAttribute('type', "text");
inputName.setAttribute('placeholder', "Name");
inputEvent.setAttribute('placeholder', "Event");
inputTime.setAttribute('placeholder', "Time");
sendWithTimer.setAttribute('type', "button");
sendWithoutTimer.setAttribute('type', "button");
sendWithTimer.setAttribute('value', "Timer");
sendWithoutTimer.setAttribute('value', "No timer");
formElement.appendChild(inputName);
formElement.appendChild(inputEvent);
formElement.appendChild(inputTime);
divContainer.appendChild(sendWithTimer);
divContainer.appendChild(sendWithoutTimer);
for (var formElementStyles = 0; formElementStyles < formElement.length; formElementStyles++) {
formElement[formElementStyles].style.display = "-webkit-flex";
formElement[formElementStyles].style.display = "flex";
formElement[formElementStyles].style.webkitFlexDirection = "column";
formElement[formElementStyles].style.flexDirection = "column";
formElement[formElementStyles].style.position = "relative";
formElement[formElementStyles].style.top = 0;
formElement[formElementStyles].style.left = 40 + "%";
formElement[formElementStyles].style.padding = 0.6 + "em";
formElement[formElementStyles].style.margin = 1 + "em";
}
var divChildNodes = divContainer.childNodes;
for (var divContainerStyles = 0; divContainerStyles < divChildNodes.length; divContainerStyles++) {
divChildNodes[divContainerStyles].style.display = "-webkit-flex";
divChildNodes[divContainerStyles].style.display = "flex";
divChildNodes[divContainerStyles].style.webkitFlexDirection = "column";
divChildNodes[divContainerStyles].style.flexDirection = "column";
divChildNodes[divContainerStyles].style.position = "relative";
divChildNodes[divContainerStyles].style.top = 0;
divChildNodes[divContainerStyles].style.left = 40 + "%";
divChildNodes[divContainerStyles].style.padding = 0.6 + "em";
divChildNodes[divContainerStyles].style.margin = 1 + "em";
divChildNodes[divContainerStyles].style.height = 10 + "em";
}
container[0].appendChild(formElement);
container[0].appendChild(divContainer);
I want to break and center after each button, any suggestions? setAttribute did not work and does not add the breaks
for (var j = 0; j <= 6; j++) {
var btn = document.createElement("BUTTON");
var t = document.createTextNode(sm[j] + " " + sy[j]);
btn.appendChild(t);
document.body.appendChild(btn);
}
jsfiddle
HTML
<div id='theParent' class='center_the_stuff'>
</div>
JS
function addInput(type, value, name, id, onclick, parentId) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.type = type;
element.value = value; // Really? You want the default value to be the type string?
element.name = name; // And the name too?
element.id = id;
element.onclick = onclick;
var parent = document.getElementById(parentId);
//Append the element in page (in span).
parent.appendChild(element);
}
function addBreak(parentId) {
var br = document.createElement("br");
var parent = document.getElementById(parentId);
parent.appendChild(br);
}
window.onload = function () {
for (var j = 0; j <= 6; j++) {
var temp = 'mybutton' + j;
addInput('button', temp, temp, temp, undefined, 'theParent');
addBreak('theParent');
}
}
CSS
.center_the_stuff {
text-align: center;
}