HTML Checkbox "onclick" Create Button issue - javascript

So i have following objectives from the checkbox click event
1] Create A Button having id = 'id-of-checkbox'+'some-character-here' in specified div
2] Clicking On That Particular Button Will Remove The Button As Well As Checkbox tick related to it
3] If User wants to remove button in specified div through unchecking the checkbox it should be done
4] And If User again checks the checkbox button should be created in specified div
Now i have achieved first 3 objectives and im having issue with 4th one , i.e
if i click on checkbox again after unticking it button is not getting created and console doesnt return any error associated with it.. please help
Here Is My HTML Code
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" class="btn" onclick="updateValue(this.id,this.name)">
Price Filter
</div>
<div id="DropArea">
</div>
Here is My Javascript Code
var objTo = document.getElementById('DropArea');
var checked = ""
function updateValue(id,name)
{
if(document.getElementById(id).checked)
{
checked='yes'
}
else if(!document.getElementById(id).checked)
{
checked='no'
}
if(checked=='yes')
{
addButton(id,name);
}
else if(checked=='no')
{
removeButton(id,name);
}
}
function addButton(id,name)
{
var nameOfButton = name+'X';
var idofButton = id+'11';
var btn = document.createElement("BUTTON");
btn.innerHTML=nameOfButton;
btn.setAttribute("class","btnCancel");
btn.setAttribute("id",idofButton);
btn.setAttribute("onclick","someMsg(this.id)")
objTo.appendChild(btn);
}
function removeButton(id,name)
{
var idofButton = id+'11'
if(document.getElementById('DropArea').contains(document.getElementById(idofButton)))
{
document.getElementById('DropArea').remove(document.getElementById(idofButton));
console.log('Button Removed');
}
}
function someMsg(id)
{
var name = id.substring(0,id.length-2);
document.getElementById(id).remove();
document.getElementById(name).checked=false;
console.log('Deleted');
}

Another approach to achieving the same result:
const dropArea = document.querySelector("#dropArea");
const checkbox = document.querySelector("#priceFilter");
checkbox.addEventListener("change", function(e) {
if (this.checked) {
const btn = createSpecificButton();
dropArea.appendChild(btn);
} else {
const btn = dropArea.querySelector("button");
dropArea.removeChild(btn);
}
});
const createSpecificButton = () => {
const btn = document.createElement("button");
btn.innerText = "Click Here";
btn.addEventListener("click", function(e) {
checkbox.checked = false;
this.remove();
});
return btn;
};
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" /> Price Filter
</div>
<div id="dropArea"></div>

Element.remove() don't have any parameters, so when you call by your way, it will remove DropArea element (includes children, like idofButton).
Solution: Change the below line
document.getElementById('DropArea').remove(document.getElementById(idofButton));
To
document.getElementById(idofButton).remove();
var objTo = document.getElementById('DropArea');
var checked = ""
function updateValue(id, name) {
if (document.getElementById(id).checked) {
checked = 'yes'
} else if (!document.getElementById(id).checked) {
checked = 'no'
}
if (checked == 'yes') {
addButton(id, name);
} else if (checked == 'no') {
removeButton(id, name);
}
}
function addButton(id, name) {
var nameOfButton = name + 'X';
var idofButton = id + '11';
var btn = document.createElement("BUTTON");
btn.innerHTML = nameOfButton;
btn.setAttribute("class", "btnCancel");
btn.setAttribute("id", idofButton);
btn.setAttribute("onclick", "someMsg(this.id)")
objTo.appendChild(btn);
}
function removeButton(id, name) {
var idofButton = id + '11'
if (document.getElementById('DropArea').contains(document.getElementById(idofButton))) {
document.getElementById(idofButton).remove();
console.log('Button Removed');
}
}
function someMsg(id) {
var name = id.substring(0, id.length - 2);
document.getElementById(id).remove();
document.getElementById(name).checked = false;
console.log('Deleted');
}
<div id="filterDropArea container">
<input type="checkbox" name="priceFilter" id="priceFilter" class="btn" onclick="updateValue(this.id,this.name)"> Price Filter
</div>
<div id="DropArea">
</div>

Related

change list item to be an input text

I am working on "to do list" using Vanilla JavaScript and stuck with edit button.
This is what I have done so far.
// console.log("Hello from inside");
const input = document.getElementById("inputText");
const display = document.getElementById("display");
const displayDone = document.getElementById("display-done");
const button = document.getElementById("addButton");
const deleteAll = document.getElementById("delete-icon");
// const ul = document.getElementById("display");
// Create and Remove list item
function createItem() {
let listItem = document.createElement("li");
listItem.className = "create";
listItem.appendChild(document.createTextNode(input.value));
display.appendChild(listItem);
input.value = "";
let editButton = document.createElement("button");
editButton.innerText = "edit";
editButton.className = "edit";
editButton.addEventListener("click", (e) => {
//console.log(e.currentTarget.parentNode);
// 1. When edit button is clicked, change list item to be an input text. <input type="text" value="my to do task"/>
// 2. Change edit button to be something like "complete" button
editButton.innerText = "complete";
// 3. When complete button is clicked, change the input item to be a list item again with the updated text.
editButton.addEventListener("click", (e) => {
editButton.innerText = "edit";
});
});
let removeTask = document.createElement("input");
removeTask.setAttribute("type", "button");
removeTask.setAttribute("value", "X");
removeTask.setAttribute("id", "removeButton");
removeTask.addEventListener("click", (e) => {
listItem.parentNode.removeChild(listItem);
});
listItem.appendChild(editButton);
listItem.appendChild(removeTask);
listItem.addEventListener("dblclick", (e) => {
displayDone.appendChild(listItem);
listItem.style.backgroundColor = "#54e346";
listItem.style.textDecoration = "line-through";
editButton.style.display = "none";
});
}
//Make sure user fill the input
function addAfterClick() {
if (input.value.length > 0) {
createItem();
} else {
alert("Write something mate!");
}
}
//List item can be added with "Enter" as well
function addWithEnter(event) {
if (event.keyCode === 13) {
addAfterClick();
}
}
// Remove all with user approve
function removeAll(event) {
let answer = prompt(`Type "Delete All" If you are that sure!`);
if (answer === "Delete All") {
display.style.display = "none";
location.reload();
} else {
alert("Try One More Time");
}
}
//Event Listeners
button.addEventListener("click", addAfterClick);
input.addEventListener("keyup", addWithEnter);
deleteAll.addEventListener("click", removeAll);
<div class="main-container">
<h2 class="title">to do list <i class="fas fa-pencil-alt"></i></h2>
<div class="content">
<input
id="inputText"
type="text"
placeholder="Add to your list..."
maxlength="20"
/>
<i id="addButton" class="fas fa-plus"></i>
<div class="remove-container">
<i id="delete-icon" class="far fa-trash-alt"></i>
<p id="remove-text">Delete All</p>
</div>
<ul id="display"></ul>
</div>
<div class="completed">
<h2 class="title-done">
completed tasks <i class="far fa-check-circle"></i>
</h2>
<ul id="display-done"></ul>
</div>
</div>
What I want to do it;
When edit button is clicked, change list item to be an input text.
Change edit button to be something like "complete" button
When complete button is clicked, change the input item to be a list item again with the updated text.
I have tried ChildNode.replaceWith() but did not work. Am I on the right path? and also what direction(s) I should follow. Thanks in advance!
My approach is to add an input field everytime you create an item:
at initial insertion hide the input field
on click on the edit button show the input and change the textNode
after you editing
console.log("Hello from inside");
const input = document.getElementById("inputText");
const display = document.getElementById("display");
const displayDone = document.getElementById("display-done");
const button = document.getElementById("addButton");
const deleteAll = document.getElementById("delete-icon");
// const ul = document.getElementById("display");
// create edit input and hide the input at first
const editInput=document.createElement("input");
editInput.setAttribute("hidden",true);
// eventhandler for editInput
function editItem(e,item){
// remove the current text node
e.target.parentNode.removeChild(e.target.parentNode.childNodes[0])
// insert at the beginning of the childNodes
e.target.parentNode.prepend( e.target.value)
e.target.setAttribute("hidden",true)
}
// Create and Remove list item
function createItem() {
let listItem = document.createElement("li");
listItem.className = "create";
listItem.appendChild(document.createTextNode(input.value));
display.appendChild(listItem);
input.value = "";
let editButton = document.createElement("button");
editButton.innerText = "edit";
editButton.className = "edit";
editInput.value=""
editButton.addEventListener("click", (e) => {
// 1. When edit button is clicked, change list item to be an input text. <input type="text" value="my to do task"/>
// 2. Change edit button to be something like "complete" button
// appended edit input
listItem.append(editInput)
if(e.target.innerText === "edit"){
editInput.removeAttribute("hidden",false)
e.target.innerText = "complete";
}else{
e.target.innerText = "edit";
}
// add the event handler for the Editinput
editInput.addEventListener("change",(e)=>editItem(e,listItem));
editInput.value=""
// 3. When complete button is clicked, change the input item to be a list item again with the updated text.
});
let removeTask = document.createElement("input");
removeTask.setAttribute("type", "button");
removeTask.setAttribute("value", "X");
removeTask.setAttribute("id", "removeButton");
removeTask.addEventListener("click", (e) => {
listItem.parentNode.removeChild(listItem);
});
listItem.appendChild(editButton);
listItem.appendChild(removeTask);
listItem.addEventListener("dblclick", (e) => {
displayDone.appendChild(listItem);
listItem.style.backgroundColor = "#54e346";
listItem.style.textDecoration = "line-through";
editButton.style.display = "none";
});
}
//Make sure user fill the input
function addAfterClick() {
if (input.value.length > 0) {
createItem();
} else {
alert("Write something mate!");
}
}
//List item can be added with "Enter" as well
function addWithEnter(event) {
if (event.keyCode === 13) {
addAfterClick();
}
}
// Remove all with user approve
function removeAll(event) {
let answer = prompt(`Type "Delete All" If you are that sure!`);
if (answer === "Delete All") {
display.style.display = "none";
location.reload();
} else {
alert("Try One More Time");
}
}
//Event Listeners
button.addEventListener("click", addAfterClick);
input.addEventListener("keyup", addWithEnter);
deleteAll.addEventListener("click", removeAll);
<div class="main-container">
<h2 class="title">to do list <i class="fas fa-pencil-alt"></i></h2>
<div class="content">
<input
id="inputText"
type="text"
placeholder="Add to your list..."
maxlength="20"
/>
<i id="addButton" class="fas fa-plus"></i>
<div class="remove-container">
<i id="delete-icon" class="far fa-trash-alt"></i>
<p id="remove-text">Delete All</p>
</div>
<ul id="display"></ul>
</div>
<div class="completed">
<h2 class="title-done">
completed tasks <i class="far fa-check-circle"></i>
</h2>
<ul id="display-done"></ul>
</div>
</div>
just a suggestion. you can use an input element for each item.
const input = document.getElementById("inputText");
const display = document.getElementById("display");
const displayDone = document.getElementById("display-done");
const button = document.getElementById("addButton");
const deleteAll = document.getElementById("delete-icon");
const createEditBtn = () => {
const editButton = document.createElement("button");
editButton.innerText = "edit";
editButton.className = "edit";
editButton.addEventListener("click", (e) => {
const btn = e.target;
const input = btn.parentElement.querySelector("input");
input.focus();
const previousVal = input.value;
input.addEventListener("keyup", (evt) => {
if (evt.keyCode === 13) {
if (input.value.trim() === "") {
input.value = previousVal;
}
input.disabled = true;
btn.disabled = false;
}
});
input.addEventListener("blur", () => {
input.disabled = true;
btn.disabled = false;
});
input.disabled = false;
btn.disabled = true;
});
return editButton;
}
const createRemoveBtn = () => {
const removeBtn = document.createElement("input");
removeBtn.setAttribute("type", "button");
removeBtn.setAttribute("value", "X");
removeBtn.addEventListener("click", (e) => {
e.target.parentElement.remove();
});
return removeBtn;
}
const createItem = () => {
const listItem = document.createElement("li");
listItem.innerHTML = `<input value="${input.value}" disabled=true>`;
display.appendChild(listItem);
input.value = "";
const editBtn = createEditBtn();
listItem.appendChild(editBtn);
listItem.appendChild(createRemoveBtn());
listItem.addEventListener("dblclick", (e) => {
displayDone.appendChild(listItem);
listItem.style.backgroundColor = "#54e346";
listItem.style.textDecoration = "line-through";
editBtn.style.display = "none";
});
}
const addAfterClick = () => {
if (input.value.length > 0) {
createItem();
} else {
alert("Write something mate!");
}
}
//List item can be added with "Enter" as well
const addWithEnter = (event) => {
if (event.keyCode === 13) {
addAfterClick();
}
}
// Remove all with user approve
const removeAll = (event) => {
const answer = prompt(`Type "Delete All" If you are that sure!`);
if (answer === "Delete All") {
display.innerHTML = "";
displayDone.innerHTML = "";
} else {
alert("Try One More Time");
}
}
//Event Listeners
button.addEventListener("click", addAfterClick);
input.addEventListener("keyup", addWithEnter);
deleteAll.addEventListener("click", removeAll);
<div class="main-container">
<h2 class="title">to do list <i class="fas fa-pencil-alt"></i></h2>
<div class="content">
<input id="inputText" type="text" placeholder="Add to your list..." maxlength="20" />
<i id="addButton" class="fas fa-plus">add Icon</i>
<div class="remove-container">
<i id="delete-icon" class="far fa-trash-alt">delete icon</i>
<p id="remove-text">Delete All</p>
</div>
<ul id="display"></ul>
</div>
<div class="completed">
<h2 class="title-done">
completed tasks <i class="far fa-check-circle"></i>
</h2>
<ul id="display-done"></ul>
</div>
</div>

Attaching Event to dynamically created element

I am working at my 'To Do List'. My goal is to create an 'delete' button inside previously created div, which contains note written by user.
The problem is that I can't use Jquery - click() because it doesn't work with dynamically created elements.
I tried to use on(), but it causes that 'delete' button appears in every note I made.
var ammleng;
var amount = [];
function ammcheck() {
if (amount.length == 0) {
return amount.length;
} else {
return amount.length++;
}
}
function Start() {
var start = document.getElementsByClassName('start')[0];
start.style.display = 'none';
var textarea = document.getElementsByClassName('textarea')[0];
textarea.classList.remove('locked');
var btn = document.getElementsByClassName('btn__container')[0];
btn.classList.remove('locked');
var text = document.getElementsByClassName('text')[0];
text.classList.add('after');
$('.notes').slideDown(2000);
}
function add() {
var txtarea = document.getElementsByClassName('textarea')[0];
ammleng = amount.length;
if (ammleng >= 13) {
alert('Za dużo notatek!')
} else if (txtarea.innerText.length < 1) {
alert('Nic nie napisałeś :(');
} else {
amount[ammcheck()] = document.getElementsByClassName('note');
var text = $('.textarea').html();
var cont = document.getElementsByClassName('notes')[0];
var ad = document.createElement('div');
var adding = cont.appendChild(ad);
adding.classList.add('note');
adding.innerText = text;
txtarea.innerText = '';
}
}
function reset() {
var els = document.getElementsByClassName('notes')[0];
els.innerHTML = '';
amount = [];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='content'>
<div class='logo'>
To Do List
</div>
<div class='text'>
<button class='start' onclick='Start()'>Zaczynajmy</button>
<div class='textarea locked' contenteditable='true' data-text='Wpisz notkę...'></div>
<div class='btn__container locked'>
<button class='dodaj' onclick='add()'>Dodaj</button>
<button class='resetuj' onclick='reset()'>resetuj</button>
</div>
</div>
<div class='notes'></div>
</div>
I tried to make it this way, but it return an error (...'appendChild() is not a function...')
var del = document.createElement('div');
del.classList.add('del');
$('.notes').on('click', '.note', function(){
$(this).appendChild(del);
})
use already existing document to bind click on
$(document).on('click', '.note', function(){
$(this).appendChild(del);
})

Dom Modification to clear Radio Button Info with Reset Button

So I have made a form that I can clear with a reset button. On this form, I have four radio buttons (that code is towards the top). When a button is selected, info comes up using "displayText".
<script type="text/javascript">
function textToDisplay (radioValue) {
console.log("textToDisplay + " + radioValue);
var displayText = "";
if (radioValue == "S") {
displayText = "Shortboards are under 7 ft in length.";
}
else if (radioValue == "L") {
displayText = "Longboards are usually between 8 and 10 ft.";
}
if (radioValue == "A") {
displayText = "Alternative boards defy easy aesthetic description.";
}
if (radioValue == "M") {
displayText = "Mid-Length surfboards are between 7 and 8 ft.";
}
return (displayText)
}
//DOM modification
function modifyDom(radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
console.log(node);
var insertnode = document.getElementById("radioButtons");
var infonode = document.getElementById("info")
if (infonode === null) {
console.log("infonode does not yet exist");
var node = document.createElement("DIV");
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
console.log(node);
insertnode.appendChild(node);
}
else {
console.log("infonode already exists");
infonode.innerHTML = displayText;
}
}
function checkboxesSelected (checkboxes, errorString) {
console.log("checkboxesSelected function");
var cbSelected = 0;
for (i=0; i<checkboxes.length; i++) {
if (checkboxes[i].checked) {
cbSelected += 1;
}
}
if (cbSelected < 2) {
return (errorString);
} else {
return "";
}
}
function validate (form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.extras, "At least TWO fin setup needs
to be selected.\n")
if (fail == "") return true
else { alert(fail); return false }
}
</script>
When I reset my page using the button,
<input type="reset" name="reset" value="Reset">
the buttons themselves are cleared but the information that appeared from selecting the button is still visible. How can I reset the page so the displayText information is not visible? Thanks!
You can use an event listener for the reset event generated by clicking the reset button to execute cleanup code.
Here's a cut down example of the technique:
"use strict";
let myForm = document.getElementById("myForm");
let infoNode = document.getElementById("infonode");
let infoText = {
"S": "small board's are good",
"L": "large board's are good too"
};
myForm.addEventListener("change", function (event) {
if(event.target.name == "size") {
infoNode.innerHTML = infoText[ event.target.value];
}
}, false);
myForm.addEventListener("reset", function (event) {
infoNode.innerHTML = "";
}, false);
<form id="myForm">
<label> <input name="size" type="radio" value = "S"> Short</label><br>
<label> <input name="size" type="radio" value = "L"> Long</label><br>
<input type="reset" value="reset">
</form>
<div id="infonode"></div>
would suggest to remove the dynamically attached div#info:
document.getElementById("info").remove();
or blank it:
document.getElementById("info").innerHTML = "";

Element text not changing when passing selected textContent and new value to an update function

I'm creating a CRUD page where the user can add, delete and edit text, but I have an issue in updating the text after I select it for edit.
In editText function when I click the edit button the text that was added will pop up inside the input field. When I click on the update button (triggering the updateText function), I can see the text in console log but the corresponding html is not updated.
HTML
<div class="main">
<form>
<input type="text" placeholder="search">
</form>
<ul></ul>
<div>
<input class="add-text" type="text" placeholder="Add Text">
<button id="add">Add</button>
<button id="update">update</button>
</div>
</div>
Javascript
const inputsearch = document.querySelector('form input');
const addInputBtn = document.querySelector('#add');
const update = document.querySelector('#update');
addInputBtn.addEventListener('click', addtext);
function addtext(){
let li = document.createElement('li');
let inputadd = document.querySelector('.add-text');
let addedtext = inputadd.value;
let h1Tag = '<h1 id="text">'+addedtext+'</h1>';
let tags = h1Tag + '<button id="delete">Delete</button><button id="edit">Edit</button>';
if(addedtext == ''){
alert('please add some text');
return;
}else{
li.innerHTML = tags;
document.querySelector('ul').appendChild(li);
}
li.querySelectorAll('#delete')[0].addEventListener('click', deleteText);
li.querySelectorAll('#edit')[0].addEventListener('click', editText);
getlist(li, h1Tag);
inputadd.value = '';
}
function deleteText(e) {
e.target.parentNode.remove();
document.querySelector('.add-text').value = '';
}
function editText(e) {
let currentText = e.target.parentNode.firstChild.textContent;
let currentValue = document.querySelector('.add-text');
currentValue.value = currentText;
getupdate(currentText, currentValue);
}
function getupdate(currentText, currentValue) {
update.addEventListener('click', updateText);
function updateText() {
currentText = currentValue.value
console.log(currentText = currentValue.value);
}
}
function getlist(li, h1Tag) {
inputsearch.addEventListener('keyup', serchText);
function serchText(e) {
let typetext = e.target.value.toLowerCase();
if(h1Tag.toLowerCase().indexOf(typetext) != -1){
li.style.display = 'block';
}else{
li.style.display = 'none';
}
}
}
To solve the issue without changing your overall approach, your edit button click needs to get the corresponding element (not just its textContent) and pass it to your getupdate() function to be updated when your update button is clicked. Relatively minor changes to your current functions:
function editText(e) {
const currentText = e.target.parentNode.firstChild;
const currentValue = document.querySelector('.add-text');
currentValue.value = currentText.textContent;
getupdate(currentText, currentValue);
}
function getupdate(currentText, currentValue) {
update.addEventListener('click', updateText);
function updateText() {
currentText.textContent = currentValue.value;
}
}
There are some other issues with your code, particularly the creation of multiple elements with the same id (which is malformed and will likely become problematic as you add additional features). Following is a snippet that addresses that issue as well as simplifying some of your functions and fixing the search.
const search = document.querySelector('form input');
const input = document.querySelector('.add-text');
const container = document.querySelector('ul');
let items = null;
let currentItem = null;
const searchItems = (event) => {
if (items) {
const s = event.currentTarget.value.toLowerCase();
for (const item of items) {
if (item.firstChild.textContent.toLowerCase().indexOf(s) !== -1) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
}
}
};
const deleteItem = (event) => {
currentItem = null;
event.currentTarget.parentNode.remove();
};
const editItem = (event) => {
currentItem = event.currentTarget.parentNode.firstChild;
input.value = currentItem.textContent;
};
const updateItem = () => {
if (currentItem) {
currentItem.textContent = input.value;
}
};
const addItem = () => {
let val = input.value
if (val) {
const li = document.createElement('li');
let inner = '<h1 class="text">' + val + '</h1>';
inner += '<button class="delete">Delete</button>';
inner += '<button class="edit">Edit</button>';
li.innerHTML = inner;
container.appendChild(li);
val = '';
currentItem = li.firstChild;
items = document.querySelectorAll('li');
for (let del of document.querySelectorAll('.delete')) {
del.addEventListener('click', deleteItem);
}
for (let edit of document.querySelectorAll('.edit')) {
edit.addEventListener('click', editItem);
}
} else {
alert('please add some text');
return;
}
};
search.addEventListener('keyup', searchItems);
document.querySelector('#add').addEventListener('click', addItem);
document.querySelector('#update').addEventListener('click', updateItem);
<div class="main">
<form>
<input type="text" placeholder="Search">
</form>
<ul></ul>
<div>
<input class="add-text" type="text" placeholder="Add Text">
<button id="add">Add</button>
<button id="update">Update</button>
</div>
</div>

Javascript: How to remove element binded to remove button (dynamic)

I am currently using an add button to add input from a text box into a list. I am also binding a button to each of these list elements and then appending them to the unordered list. How do I remove the element onclick of the corresponding remove button? Pure JavaScript only.
window.onload = function() {
var elements = [];
var textInput;
document.getElementById("addButton").onclick = function() {
textInput = document.getElementById("inputBox").value;
if (textInput == "") {
alert("Make sure your input is not empty!");
} else {
var liNode = document.createElement('li');
var btnNode = document.createElement('button');
var btnText = document.createTextNode("Remove Item");
btnNode.appendChild(btnText);
var textNode = document.createTextNode(textInput);
liNode.appendChild(textNode);
liNode.appendChild(btnNode);
document.getElementById("myInputList").appendChild(liNode);
}
}
function addElementToList(element) {
if (element != "") {
elements.push(element);
} else {
alert("Make sure the input field is not empty!")
}
}
}
<!DOCTYPE html>
<html>
<body>
<head>
<script src="func.js"></script>
</head>
<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>
</body>
</html>
Use addEventListener to register click event over created button.
Use .remove(), removes the object from the tree it belongs to.
Try this:
window.onload = function() {
var elements = [];
document.getElementById("addButton").onclick = function() {
var textInput = document.getElementById("inputBox").value;
if (textInput == "") {
alert("Make sure your input is not empty!");
} else {
var liNode = document.createElement('li');
var btnNode = document.createElement('button');
var btnText = document.createTextNode("Remove Item");
btnNode.appendChild(btnText);
var textNode = document.createTextNode(textInput);
liNode.appendChild(textNode);
liNode.appendChild(btnNode);
document.getElementById("myInputList").appendChild(liNode);
btnNode.addEventListener('click', removeHandler);
}
}
function removeHandler() {
this.parentNode.remove(); // this will be `button` element and `parentNode` will be `li` element
}
function addElementToList(element) {
if (element != "") {
elements.push(element);
} else {
alert("Make sure the input field is not empty!")
}
}
}
<input type="text" id="inputBox">
<br>
<button id="addButton">Add</button>
<br>
<br>
<ul id="myInputList"></ul>

Categories