Add and Remove button JavaScript [duplicate] - javascript

This question already has answers here:
How to remove an HTML element using Javascript?
(11 answers)
Closed 5 years ago.
I need make button to add and remove that adds and removes inputs.
Did I write normal script or adding button should be another?
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function() {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
});
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>

I made some modifications to Anu's answer, but this should do the trick.
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function() {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
var btn = document.createElement("BUTTON");
var t = document.createTextNode("X");
btn.id = i;
btn.appendChild(t);
btn.onclick = function() {
$('#' + i).remove();
$('#' + i).remove();
i = i - 1;
};
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
div.appendChild(btn);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>

const addButton = document.getElementById("add");
const hobbyWrapper = document.getElementById("hobby");
let i = 0
addButton.addEventListener("click", add);
function add (){
i = i + 1
const inputWrapper = document.createElement('div');
inputWrapper.id = `inputWrapper-${i}` ;
const input = document.createElement('input');
input.placeholder = "More hobbies";
inputWrapper.appendChild(input)
const removeButton = document.createElement('button');
removeButton.innerHTML = 'X';
removeButton.onclick = () => {
hobbyWrapper.removeChild(inputWrapper)
}
inputWrapper.appendChild(removeButton);
hobbyWrapper.appendChild(inputWrapper);
}
<div id="hobby">
<div id="inputWrapper">
<input placeHolder="Type your hobby">
<button>X</button>
</div>
</div>
<button id="add">Add hobby</button>

var div = document.getElementById('hobby');
function addHobby() {
var input = document.createElement('input'),
button = document.createElement('button');
input.placeholder = "More hobbies";
button.innerHTML = 'X';
// attach onlick event handler to remove button
button.onclick = removeHobby;
div.appendChild(input);
div.appendChild(button);
}
function removeHobby() {
// remove this button and its input
div.removeChild(this.previousElementSibling);
div.removeChild(this);
}
// attach onclick event handler to add button
document.getElementById('add').addEventListener('click', addHobby);
// attach onclick event handler to 1st remove button
document.getElementById('remove').addEventListener('click', removeHobby);
<div id="hobby">
<input placeHolder="Type your hobby" />
<button id="remove">X</button>
</div>
<button id="add">Add hobby</button>

const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function(){
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
var button = document. createElement("button");
button. innerHTML = "X";
button.id=i;
button.onclick = function() {
div.removeChild(document.getElementById(button.id));
div.removeChild(button)
}
div.appendChild(button);
});
<div id="hobby">
<input placeHolder="Type your hobby">
<button>X</button>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>

I think I see where you are going with this, add and remove hobbies.
Note for simplicity I wrap each group in a span, then add/remove that span.
I did NOT put a remove on the first one, you might do that IF you wanted to make it removable.
const addHobby = document.getElementById("add");
var i = 0;
const hobbydiv = document.getElementById("hobby");
addHobby.addEventListener("click", function() {
i++;
const newspan = document.createElement('span');
newspan.className = "groupthing";
const removeButton = document.createElement('button');
removeButton.addEventListener('click', function(e) {
e.target.closest(".groupthing").remove();
});
removeButton.className = "deleteus";
removeButton.innerHTML = "X";
const editInput = document.createElement('input');
editInput.id = i;
editInput.placeholder = "More hobbies";
newspan.appendChild(editInput);
newspan.appendChild(removeButton);
hobbydiv.appendChild(newspan);
});
.deleteus{color:red;}
<div id="hobby">
<span class="groupthing">
<input placeHolder="Type your hobby" />
<button class="deleteus">X</button>
</span>
<!--Remove button-->
</div>
<button id="add">Add hobby</button>

To add button,
const add = document.getElementById("add");
var i = 0;
const div = document.getElementById("hobby");
add.addEventListener("click", function () {
i++;
const edit = document.createElement('input');
edit.id = i;
edit.placeholder = "More hobbies";
var btn = document.createElement("BUTTON");
btn.id = i;
var t = document.createTextNode("X");
btn.appendChild(t);
//Also I need add remove button for each input, which removes its input
div.appendChild(edit);
div.appendChild(btn);
btn.addEventListener("click", function () {
div.removeChild(document.getElementById(btn.id));
div.removeChild(btn);
});
});

Related

What am doing wrong in here?

Input value always gets into if condition first even am parsing it to parseInt() and when page refreshed with a number it gets into else condition, like its not registering the inputValue at first place, also if i add a submit event rather an click one event doesnt fires up.
HTML
<div class="addHere"></div>
<div class="inputs">
<input type="text" maxlength="1" class="inputValue" placeholder="insert numbers:"/>
<button class="btn">+</button>
</div>
javaScript
// this line was modified
const inputValue = parseInt(document.querySelector(".inputValue").value);
const div = document.querySelector(".addHere");
document.querySelector(".btn").addEventListener("click", addInputs);
fucntion addInputs() {
if(isNaN(inputValue)) {
alert("Wrong input");
} else {
for ( let i = 1; i <= inputValue; i++) {
const form = document.createElement("form");
form.method = "post";
form.action = "#";
const input1 = document.createElement("input");
input1.type = "text";
input1.maxLength = "12";
input1.className = "factor";
input1.required = true;
const input2 = document.createElement("input");
input2.type = "text";
input2.maxLength = "1";
input2.className = "priority";
input2.required = true;
const br = document.createElement("br");
form.appendChild(br.cloneNode());
form.appendChild(input1);
form.appendChild(input2);
form.appendChild(br.cloneNode());
div.appendChild(form);
}
const sub = document.createElement("button");
sub.type = "submit";
sub.value = "Submit";
sub.className = "subButton";
sub.textContent = "Submit";
div.appendChild(sub);
}
}
const inputValue = parseInt(document.querySelector(".inputValue").value);
Is being executed once, so every time you click on + button it won't read value of the tag. You have to move this statement inside you click handler, like this:
function addInputs() {
// this should be here, so every time you click on + button, actuall values is being read
const inputValue = parseInt(document.querySelector(".inputValue").value);
if (isNaN(inputValue)) {
alert("Wrong input");
} else {
for (let i = 1; i <= inputValue; i++) {
const form = document.createElement("form");
...
Also here:
const div = document.querySelector(".addHere");
I could not find div with such class in your HTML, so you have to add it like this, I think:
<div class="inputs">
<input type="text" maxlength="1" class="inputValue" placeholder="insert numbers:" />
<button class="btn">+</button>
</div>
<div class="addHere"> </div>
You're recording the value of the input on page load, so at first it is empty.
Move this line
const inputValue = parseInt(document.querySelector(".inputValue").value);
to be the first line of your function that runs after clicking your button.
function addInputs() {
const inputValue = parseInt(document.querySelector(".inputValue").value);
Also it is probably best to use ID's for those elements and select them by their ID's rather than a class. ID's are unique so there can only be one of them on the page.
I also corrected typos in those lines, missing " and misspelled function.
You forgot an " in the first line in javascript code.
const inputValue = parseInt(document.querySelector(".inputValue").value);
const div = document.querySelector(".addHere");
document.querySelector(".btn").addEventListener("click", addInputs);
function addInputs() {
const inputValue = parseInt(document.querySelector(".inputValue").value);
for (let i = 1; i <= inputValue; i++) {
const form = document.createElement("form");
form.method = "post";
form.action = "#";
const input1 = document.createElement("input");
input1.type = "text";
input1.maxLength = "12";
input1.className = "factor";
input1.required = true;
const input2 = document.createElement("input");
input2.type = "text";
input2.maxLength = "1";
input2.className = "priority";
input2.required = true;
const br = document.createElement("br");
form.appendChild(br.cloneNode());
form.appendChild(input1);
form.appendChild(input2);
form.appendChild(br.cloneNode());
div.appendChild(form);
}
const sub = document.createElement("button");
sub.type = "submit";
sub.value = "Submit";
sub.className = "subButton";
sub.textContent = "Submit";
div.appendChild(sub);
}
<div class="addHere"></div>
<div class="inputs">
<input type="number" min="0" max="9" class="inputValue" placeholder="insert numbers:" />
<button class="btn">+</button>
</div>

How put button into variable when it appears after page onload

How can I get the button add__deal__btn after it appears? When the page loads add__deal__btn doesn't exist, but after I add the task__card to the div it appears. How can I manipulate the button after it appears?
let addTitle = document.querySelector('.add__title');
let addBtn = document.querySelector('.add__btn');
let tasks = document.querySelector('.tasks');
let addDealBtn = [];
addBtn.onclick = function() {
let task = document.createElement('div');
task.className = 'task__card';
let taskTitle = document.createElement("h4");
taskTitle.innerHTML = addTitle.value
task.appendChild(taskTitle)
addDealBtn = document.createElement("button");
addDealBtn.className = "add__deal__btn";
addDealBtn.innerHTML = "Add deal";
task.appendChild(addDealBtn);
tasks.append(task);
}
//THIS CODE DOESN'T WORK
addDeal = document.querySelectorAll('.add__deal__btn');
for(let i = 0;i<addDeal.length;i++){
addDeal[i].onclick= function(){
alert();
}
}
<div class="add">
<input type="text" class="add__title">
<br>
<button class="add__btn">Add</button>
</div>
<div class="tasks"></div>
Thank you
Add the onclick event when you create the button.
let addTitle = document.querySelector('.add__title');
let addBtn = document.querySelector('.add__btn');
let tasks = document.querySelector('.tasks');
let addDealBtn = [];
addBtn.onclick = function() {
let task = document.createElement('div');
task.className = 'task__card';
let taskTitle = document.createElement("h4");
taskTitle.innerHTML = addTitle.value
task.appendChild(taskTitle)
addDealBtn = document.createElement("button");
addDealBtn.className = "add__deal__btn";
addDealBtn.innerHTML = "Add deal";
// Add onclick event here
addDealBtn.onclick = function() {
alert('Button clicked!');
};
task.appendChild(addDealBtn);
tasks.append(task);
}
<div class="add">
<input type="text" class="add__title">
<br>
<button class="add__btn">Add</button>
</div>
<div class="tasks"></div>
The line addDeal = document.querySelectorAll('.add__deal__btn'); only runs once (when the script loads). At that time, no <button> elements with class add__deal__btn exist in the DOM.
To achieve what you want simply add the event listener to each newly generated button. Like this:
let addTitle = document.querySelector('.add__title');
let addBtn = document.querySelector('.add__btn');
let tasks = document.querySelector('.tasks');
addBtn.onclick = function () {
let task = document.createElement('div');
task.className = 'task__card';
let taskTitle = document.createElement("h4");
taskTitle.innerText = addTitle.value;
task.appendChild(taskTitle);
let addDealBtn = document.createElement("button");
addDealBtn.className = "add__deal__btn";
addDealBtn.innerText = "Add deal";
task.appendChild(addDealBtn);
tasks.append(task);
addDealBtn.onclick = function() {
alert('Hey it works!');
};
}
<div class="add">
<input type="text" class="add__title">
<br>
<button class="add__btn">Add</button>
</div>
<div class="tasks"></div>
Tip: You don't need to create an array to store each new button you create anymore.

when I click on a element returns multiple times

this is my code(without css file):
var taskInput = document.getElementById("taskInput"),
taskList = document.getElementById("taskList");
taskList.addEventListener("click", changesLi);
function addTask() {
if (!taskInput.value) return alert("Please enter a task.");
var li = createLi(taskInput.value);
taskList.prepend(li);
taskInput.value = "";
}
function createLi(title) {
var li = document.createElement("li"),
span = document.createElement("span"),
div = document.createElement("div"),
remove = document.createElement("a"),
done = document.createElement("a"),
doneImg = document.createElement("img"),
removeImg = document.createElement("img");
span.textContent = title;
li.className = "task";
div.className = "links";
done.href = "#";
done.className = "done";
doneImg.alt = "done";
done.appendChild(doneImg);
remove.href = "#";
remove.className = "remove";
removeImg.alt = "remove";
remove.appendChild(removeImg);
li.appendChild(span);
li.appendChild(div);
div.appendChild(done);
div.appendChild(remove);
return li;
}
function changesLi(e) {
if (e.target.parentElement.classList.contains("remove")) {
e.target.parentElement.parentElement.parentElement.remove();
}
if (e.target.parentElement.classList.contains("done")) {
const tasks = document.querySelectorAll(".done");
tasks.forEach(task => {
task.addEventListener("click", function() {
console.log(e.target);
});
});
}
}
<form class="task-form" onsubmit="event.preventDefault();addTask()">
<input id="taskInput" placeholder="New task..." autocomplete="off" />
<input type="submit" value="Add Task" class="submit" />
</form>
<ul id="taskList"></ul>
When I click on a button that contains the done class, the e.target value returns to me as an array each time.
The first time I click, nothing returns. The second time, it returns the target once, the third time, the target twice, and so on...
No matter how much I searched, I didn't get any results. Where is my problem?
Whenever the user clicks on a done button, you're adding a click listener to all the done buttons. Adding a listener doesn't replace previous listeners, so each time they click it adds another listener. When they click again, it runs all the listeners that do the console.log(e.target), as well as the original listener that adds another listener to all the buttons.
You should just log what you want in the original listener, without adding any additional listeners.
var taskInput = document.getElementById("taskInput"),
taskList = document.getElementById("taskList");
taskList.addEventListener("click", changesLi);
function changesLi(e) {
if (e.target.parentElement.classList.contains("remove")) {
e.target.parentElement.parentElement.parentElement.remove();
} else if (e.target.parentElement.classList.contains("done")) {
console.log(e.target.parentElement.parentElement.parentElement.querySelector("span").textContent);
}
}
function addTask() {
if (!taskInput.value) return alert("Please enter a task.");
var li = createLi(taskInput.value);
taskList.prepend(li);
taskInput.value = "";
}
function createLi(title) {
var li = document.createElement("li"),
span = document.createElement("span"),
div = document.createElement("div"),
remove = document.createElement("a"),
done = document.createElement("a"),
doneImg = document.createElement("img"),
removeImg = document.createElement("img");
span.textContent = title;
li.className = "task";
div.className = "links";
done.href = "#";
done.className = "done";
doneImg.alt = "done";
done.appendChild(doneImg);
remove.href = "#";
remove.className = "remove";
removeImg.alt = "remove";
remove.appendChild(removeImg);
li.appendChild(span);
li.appendChild(div);
div.appendChild(done);
div.appendChild(remove);
return li;
}
<form class="task-form" onsubmit="event.preventDefault();addTask()">
<input id="taskInput" placeholder="New task..." autocomplete="off" />
<input type="submit" value="Add Task" class="submit" />
</form>
<ul id="taskList"></ul>
Each time you click a '.done' element, you are binding a new click event to each '.done' element:
if (e.target.parentElement.classList.contains("done")) {
const tasks = document.querySelectorAll(".done");
// for each '.done'
tasks.forEach(task => {
// add another callback for the click event
task.addEventListener("click", function() {
console.log(e.target);
});
});
}
And you don't need to do that. Just log the target:
if (e.target.parentElement.classList.contains("done")) {
console.log(e.target);
}

Unable to remove checkbox with JavaScript

Actually, I want to remove a specific checkbox div from at any time.
As trying to give a functionality that a user can add or remove a checkbox perfectly.
I wrote the code I try to add or rest the check box but when I try to remove the checkbox it does not work and I am not figuring out what is the problem.
Can someone fix it?
function uncheckAll2() {
var inputs = document.querySelectorAll('input[name="todo[]"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
function addItem() {
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');
var div = document.createElement('div'); //li
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = 1;
checkbox.name = "todo[]";
checkbox.className = "textt";
div.appendChild(checkbox);
var text = document.getElementById('texto');
div.appendChild(document.createTextNode(text.value));
li.appendChild(div);
ul.appendChild(li);
}
function addElement(elementId, html) {
// Adds an element to the document
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
}
var checkId = 0;
function addcheck() {
checkId++; // increment fileId to get a unique ID for the new element
var html = 'Remove';
addElement( checkId, html);
}
var button = document.getElementById('btn');
button.onclick = addItem , addcheck() ;
<body>
<h1>Add or remove element</h1>
<hr>
<br>
<ul id="ul">
</ul>
</div>
<button type="button" id="btn" onclick="addItems , addFile() ">Add More</button>
<input type="text" id="texto">
<input type="button" onclick="uncheckAll2()" class="btn btn-link" value="Reset">
here is the working code ok Eddie ?
function uncheckAll2() {
var inputs = document.querySelectorAll('input[name="todo[]"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
}
function removeElement(linkElement) {
// Removes an element from the document
var element = linkElement.parentNode.parentNode;//to get to the li element
element.parentNode.removeChild(element);
}
function addItem() {
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');
var div = document.createElement('div'); //li
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = 1;
checkbox.name = "todo[]";
checkbox.className = "textt";
div.appendChild(checkbox);
var text = document.getElementById('texto');
div.appendChild(document.createTextNode(text.value));
addcheck(div)
li.appendChild(div);
ul.appendChild(li);
}
function addElement(div,elementId, html) {
// Adds an element to the document
div.setAttribute('id', elementId);
div.innerHTML += html;
}
var checkId = 0;
function addcheck(div) {
checkId++; // increment fileId to get a unique ID for the new element
var html = '<a class="link" href="" onclick="javascript:removeElement( this ); return false;">Remove</a>';
addElement( div, checkId, html);
}
var button = document.getElementById('btn');
button.onclick = addItem ;
add this css for just readability but i think you will add more to the css
<style>
.link{
padding-left: 10px;
}
</style>
There is a way to do it with a single function:
<body>
<h1>Add or remove element</h1>
<hr>
<br>
<div>
<ul id="ul">
</ul>
</div>
<button type="button" id="btn" onclick="addItem()">Add More</button>
<input type="text" id="texto">
<input type="button" onclick="uncheckAll2()" class="btn btn-link" value="Reset">
</body>
</html>
<script type="text/javascript">
function uncheckAll2() {
var inputs = document.querySelectorAll('input[name="todo[]"]');
for (var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
}
}
var checkId = 0;
function addItem() {
var ul = document.getElementById('ul'); //ul
var li = document.createElement('li');
var div = document.createElement('div'); //li
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.value = 1;
checkbox.name = "todo[]";
checkbox.className = "textt";
li.id = checkId;
removeLink = 'Remove';
checkId++;
div.appendChild(checkbox);
var text = document.getElementById('texto');
div.appendChild(document.createTextNode(text.value));
div.innerHTML+=removeLink;
li.appendChild(div);
ul.appendChild(li);
}
</script>

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);
}

Categories