Delete element in JS - javascript

I was trying to prototype a site for a To-Do List to experiment with something new using JavaScript.
function task() {
//Create checkbox
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
//Create <br>
lineBreak = document.createElement("br");
//Create <p> element
var todo = document.createElement("p");
//Insert in <p> the text in the input box
todo.innerText = document.getElementById("task").value;
//Create the <p>checkbox+text</p><br> on every botton click
return document.body.appendChild(x) + document.body.appendChild(todo) + document.body.appendChild(lineBreak);
document.querySelector('#reset').addEventListener('click', () => {
document.getElementById('reset').clicked
});
}
//Show Reset button on task generated
document.querySelector('#go').addEventListener('click', () => {
document.getElementById("reset").style.visibility = "visible";
});
p {
display: inline;
}
img {
width: 30px;
display: inline;
}
#reset {
visibility: hidden;
}
<h1>To-Do List</h1>
<input type="text" placeholder="Write a Task" id="task"><button id="go" onclick="task()">GO</button>
<hr>
<body>
<section>
<button id="reset">RESET</button>
</section>
</body>
As you can see from the code and the indicated if statement I was able to generate for each click on the go button (defined in HTML) new <p></p>.
It successfully generates a checkbox, next to a text typed in a text box and then wraps with the <br>.
I was trying to eliminate the elements generated by pressing the reset button, but despite having tried several solutions the only one that seems to work is the one that deletes all the contents of the body.
Could you suggest a solution to allow it to work?

Just make the adjustments to your javascript code with the following steps and it should work as your expectation:
Steps to fix the code:
Step 1: AddEventListener should be called before return so it would be called whenever the task() is executed with the click of the Go button.
Step 2: Firstly, remove the className "go-element" from the previously added elements if they exist.
Step 3: Add the class "go-element" to newly added elements so they can be identified easily while resetting them.
Step 4: on reset click, it should remove all the elements with the class "go-element"
Note: If you just want to remove all the elements which are added through the Go button, just skip step 2. Also, to simplify you can wrap your all elements in a div element and just follow all the steps as shown above with the div instead of elements.
function task() {
// Step 2: removing go-element class from previously added elements
const elements = document.getElementsByClassName("go-element");
while(elements.length > 0) {
elements[0].classList.remove("go-element");
}
// Step 3: add the class name to new elements
//Create checkbox
var x = document.createElement("INPUT");
x.setAttribute("type", "checkbox");
x.classList.add("go-element"); // step 3
//Create <br>
lineBreak = document.createElement("br");
lineBreak.classList.add("go-element"); // step 3
//Create <p> element
var todo = document.createElement("p");
todo.classList.add("go-element"); // step 3
//Insert in <p> the text in the input box
todo.innerText = document.getElementById("task").value;
// Step 1: moved this code before return so it will execute
document.querySelector('#reset').addEventListener('click', () => {
// Step 4: removing elements with class name "go-element"
const elements = document.getElementsByClassName("go-element");
while (elements.length > 0) {
elements[0].parentNode.removeChild(elements[0]);
}
});
//Create the <p>checkbox+text</p><br> on every botton click
return document.body.appendChild(x) + document.body.appendChild(todo) + document.body.appendChild(lineBreak);
}
//Show Reset button on task generated
document.querySelector('#go').addEventListener('click', () => {
document.getElementById("reset").style.visibility = "visible";
});

Related

onclick function doesn't execute

I'm trying to update the number of participants by increasing it by one every time the submit button gets clicked, and by doing so I added an add() inside my script tag and increased the participant number every time it gets clicked. But the number of participants doesn't get changed for some reason.
Btw I'm new to DOM and JS
let Agenda_style = document.querySelector('.agenda'); //to add style you must acess the class name/ID using querySelector
Agenda_style.style.color = "red "; // set color to red to change the color of the class agenda
let NewElement = document.createElement("li "); //create new element of type <li>
NewElement.innerText = "Here "; // add a text inside the <li> element
Agenda_style.append(NewElement); // append a tet to the agendaa class
let participant = 0;
function add() {
participant++;
document.getElementById("submit").innerText = participant;
};
<h5>Number of participant:<span id="submit">0</span></h5>
<button type="button" onclick="add()">Submit</button>
</div>
It fails for me, as I have now .agenda element.. do you have that in your HTML?
If I put a null check around that section of the script, the remaining piece works.
<h5>Number of participants: <span id="submit">0</span></h5>
<button type="button" onclick="add()">Submit</button>
</div>
<script>
let Agenda_style = document.querySelector('.agenda'); // to add style you must access the class name/ID using querySelector
if(Agenda_style != null) { // only proceed if Agenda_style exists
Agenda_style.style.color = "red "; // set color to red to change the color of the class agenda
let NewElement = document.createElement("li "); // create new element of type <li>
NewElement.innerText = "Here "; // add a text inside the <li> element
Agenda_style.append(NewElement); // append a tet to the agendaa class
}
let participant = 0;
function add() {
participant++;
document.getElementById("submit").innerText = participant;
}
</script>
These days we tend to not use inline JavaScript, so it would be best to grab your button with querySelector, and then use addEventListener to call your function when it's clicked. This way there's a "separation of concerns" between your mark-up, your CSS, and your code.
const number = document.querySelector('#number');
const button = document.querySelector('button');
button.addEventListener('click', add, false);
let participant = 0;
function add() {
number.textContent = ++participant;
}
<h5>Number of participant:
<span id="number">0</span>
</h5>
<button type="button">Submit</button>
This should be working
function add() {
let val = document.querySelector('#submit').innerText;
val = parseInt(val)+1;
}

How to delete text box along with button in JavaScript

I have a button when user clicks the button it create the text box along with remove button
but all the text boxes created with same id how we can delete the text box when clicks respective remove button
here My Code:
<body>
<button type="button" id="URLbtn" onclick="Createinput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
<script>
function Createinput() {
var newdiv=document.createElement("div");
newdiv.id="test"
var Inputele=document.createElement("input");
Inputele.type="text";
Inputele.id="URLtxt"
newdiv.appendChild(btnele);
var btnele=document.createElement("button");
btnele.id="rmvbtn"
btnele.type="button"
btnele.innerHTML="-"
btnele.onclick=RemoveUrlBox()
newdiv.appendChild(btnele);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newdiv);
}
function RemoveUrlBox() {}
</script>
</body>
i am getting following output
if user click 2 remove button only remove the second textbox and button
You need to select the wrapping div. Easiest way is to use remove() and use closest. No need to use the id..... You also need to remember ids need to be unique.
function createInput() {
var newDiv = document.createElement("div");
newDiv.className = 'group';
var inputElem = document.createElement("input");
inputElem.type = "text";
newDiv.appendChild(inputElem);
var btnElem = document.createElement("button");
btnElem.type = "button";
btnElem.textContent = "-";
btnElem.addEventListener("click", removeUrlBox);
newDiv.appendChild(btnElem);
var element = document.getElementById("TextAreaBtn");
element.appendChild(newDiv);
}
function removeUrlBox() {
this.closest('.group').remove();
}
<button type="button" id="URLbtn" onclick="createInput()"> + Add URL</button>
<div id="TextAreaBtn"></div>
This should do the trick:
const txtarea=document.getElementById('TextAreaBtn');
document.getElementById('URLbtn').onclick=()=>txtarea.innerHTML+=
'<div><input type="text" class="URLtxt"><button class="rmvbtn">-</button></div>';
txtarea.onclick=ev=>ev.target.className==="rmvbtn"&&ev.target.parentNode.remove()
<button type="button" id="URLbtn"> + Add URL</button>
<div id="TextAreaBtn"></div>
I replaced your id attributes with class attributes, as these don't need to be unique.
I reduced your script by using innerHTML instead of laboriously putting elements together with createElement(). This is a matter of opinion as both methods have their advantages.
I also used delegated event listener attachment for the removal buttons. This way you can get away with a single event listener on div.TextAreaBtn. The attached funcion will only trigger any action if the clicked element has class "rmvbtn".
Change
btnele.onclick=RemoveUrlBox()
to
btnele.addEventListener('click', function (e) {
// `this` is the button that was clicked no matter about the id
// `this.parentNode` is the div you want to remove
const nodeToRemove = this.parentNode;
nodeToRemove.parentNode.removeChild(nodeToRemove);
});

Saving only the first word of a paragraph in a javascript variable

I am trying to store a paragraph in a javascript variable. I have multiple buttons inside a table, each one of the buttons has a different value, the value of each button is a small text paragraph. When i click a button a save the current buttons value in a javascript variable called 'input'.
When a button is clicked i also load an html form called "contactForm" and i display the buttons value inside that form.
The functionality works fine, the problem though is that when i save the value of the button in the ('input') js variable it saves only the first word of the paragraph, is there a way to fix this?
<html>
<div id="contactForm" >
<p><h4><i>First Choose the clients and then the file which will be uploaded in order to proced</i></h4></2>
<hr>
<input type="text" id="someInput" name="someInput"></input>
<hr>
</div>
<script>
var input; //prepare var to save contact name/ PLACE outside document ready
$(function() {
// contact form animations
$('button[id="contactbutton"]').click(function() {
input = $(this).val(); //set var input to value of the pressed button
document.getElementById("someInput").value = input;
$('#contactForm').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
</script>
<html>
It's simple and it works... I just didn't include the additional jQuery that you've written, as for getting the first word from a paragraph, it does do that though.
<div id="contactForm" >
<p>First Choose the clients and then the file which will be uploaded in order to proced</p>
<hr>
<input type="text" id="someInput" name="someInput">
<hr>
</div>
<br>...
<br>
<h4>Demo</h4>
<button id ="contactbutton">Click Me</button>
<script>
/**
* #description the purpose of this function is to demonstrate how to
* get the first word of a paragraph, sentence, etc.
*/
!function() {
var btn = document.querySelector('button[id="contactbutton"]');
btn.addEventListener("click", function(){
// get the paragraph tag text
var para = document.querySelector("#contactForm p").textContent;
console.log(para);
// break the paragraph into an arraywor each word seperated by a space
// index 0 = first element in the array
var word = para.split(" ")[0];
console.log(word);
// another example
var inp = document.querySelector("input#someInput");
var inpVal = inp.value;
console.log(inpVal);
var word2 = inpVal.split(" ")[0];
console.log(word2);
});
}();
</script>

Javascript- Creating To Do list not working

I deleted the button part in my script but not even the first part of my function is working where I type in input box and suppose to be added to the ...I don't understand why. When I run the code without the buttons code which is titled " //BUTTON creation " I get no error but no item is being added to the list. So I have two problems Items aren't being added to my list and aren't displaying and also if I include the button part its saying an error "list.appendChild is not a function"
<input type="text" placeholder="Enter an Activity" id="textItem">
<img src="images/add-button.png" id="addButton">
<div id="container">
<ul class="ToDo">
<!--
<li>
This is an item
<div id="buttons">
<button ></button>
<img src="images/remove-icon.png"id="remove">
<button id="complete"></button>
<img src="images/complete-icon.jpg" id="complete">
</div>
</li>
!-->
</ul>
</div>
<script type="text/javascript">
//Remove and complete icons
var remove = document.createElement('img').src =
"images/remove-icon.png";
var complete = document.createElement('img').src = "images/complete-icon.jpg";
//user clicks add button
//if there is text in the item field we grab the item into var text
document.getElementById("addButton").onclick = function()
{
//value item is the text entered by user
var value = document.getElementById("textItem").value;
//checks if there is a value typed
if(value)
{
addItem(value);
}
//adds a new item to the ToDo list
function addItem(text)
{
var list = document.getElementsByClassName("ToDo");
//created a varibale called item that will create a list item everytime this function is called
var item = document.createElement("li");
//this will add to the innerText of the <li> text
item.innerText = text;
//BUTTON creation
var buttons = document.createElement('div');
buttons.classList.add('buttons');
var remove = document.createElement('buttons');
buttons.classList.add('remove');
remove.innerHTML = remove;
var complete = document.createElement('buttons');
buttons.classList.add('complete');
complete.innerHTML = complete;
buttons.appendChild(remove);
buttons.appendChild(complete);
list.appendChild(buttons);
list.appendChild(item);
}
}
</script>
The problem is in the line:
var list = document.getElementsByClassName("ToDo");
list.appendChild(item);
The line var list = document.getElementsByClassName("ToDo"); will provide a collection, notice the plural name in the api.
You need to access it using :
list[0].appendChild(item);
There are other problems too in the code but hopefully this gets you going!
There are a couple of issues in your code that need to be addressed to get it to work properly.
1) You are creating your image elements and then setting the variables to the src name of that image and not the image object itself. When you use that reference later on, you are only getting the image url and not the element itself. Change var remove = document.createElement('img').src = "images/remove-icon.png" to this:
var removeImg = document.createElement('img')
removeImg.src = "images/remove-icon.png";
2) As #Pankaj Shukla noted, inside the onclick function, getElementsByClassName returns an array, you will need to address the first item of this array to add your elements. Change var list = document.getElementsByClassName("ToDo") to this:
var list = document.getElementsByClassName("ToDo")[0];
3) For your buttons, you are trying to creating them using: var remove = document.createElement('buttons'). This is invalid, buttons is an not the correct element name, its button. Additionally, you are re-declaring the variables remove and complete as button objects, so within the onclick function it reference these buttons, not the images you defined earlier. So when you assign the innerHTML to remove and complete, you are assigning the buttons innerHTML to itself. The solution is to change the image variables to something different.
4) Finally, also relating to the buttons, you are assigning the innnerHTML to an image object, that's incorrect. You can either insert the html text of the img directly, or append the image object as a child of the button, similar to how the button is a child of the div.
The updated code with all these changes looks like this:
//Remove and complete icons
var removeImg = document.createElement('img');
removeImg.src = "images/remove-icon.png";
var completeImg = document.createElement('img');
completeImg.src = "images/complete-icon.jpg";
//user clicks add button
//if there is text in the item field we grab the item into var text
document.getElementById("addButton").onclick = function() {
//value item is the text entered by user
var value = document.getElementById("textItem").value;
//checks if there is a value typed
if (value) {
addItem(value);
}
//adds a new item to the ToDo list
function addItem(text) {
var list = document.getElementsByClassName("ToDo")[0];
//created a varibale called item that will create a list item everytime this function is called
var item = document.createElement("li");
//this will add to the innerText of the <li> text
item.innerText = text;
//BUTTON creation
var buttons = document.createElement('div');
buttons.classList.add('buttons');
var remove = document.createElement('button');
remove.classList.add('remove');
remove.appendChild(removeImg);
var complete = document.createElement('button');
complete.classList.add('complete');
complete.appendChild(completeImg);
buttons.appendChild(remove);
buttons.appendChild(complete);
list.appendChild(buttons);
list.appendChild(item);
}
}

HTML list, Adding JQuery to cross selected item.

I have a little app that adds items to a list. The items appear with a button next to them, I want to be able to press that button to add a (text-decoration: line-through). I have tried a few different things but nothing seems to work (the Javascript to add items, delete the last item, add classes to the new li elements, etc. All that works fine, my problem is only with the JQuery part, more comments on the code itself).
HTML
<html>
<body>
<h1> Shopping List </h1>
<button id="add"> Add </button>
<input type="text" id="input" placeholder="Enter Items"> </input>
<button id="remove"> Remove Last </button>
<ul id="list">
</ul>
</body>
</html>
Js/Jq:
document.getElementById("add").addEventListener('click', function() {
var check = document.createElement("button");
var input = document.getElementById("input").value;
var newEl = document.createElement("li");
var newText = document.createTextNode(input);
var buttonText = document.createTextNode("Check");
newEl.className = "liEl";
newEl.appendChild(newText);
newEl.appendChild(check);
check.setAttribute("class", "checked");
check.appendChild(buttonText);
/* Problem starts here */
$("button.checked").on('click', function() {
$('li.liEl').css('text-decoration: line-through');
/* It should get the button with the class "checked" and on click, make the li elements with class "liEl" to have that css... */
}
);
var position = document.getElementsByTagName("ul")[0];
position.appendChild(newEl);
document.getElementById("input").value = "";
document.getElementById('input').onkeypress = function(e) {
if (e.keyCode == 13) {
document.getElementById('add').click(); /* adds an event listener to the submit text, keyCode 13 equals the enter key so when it's pressed it presses the add button. */
}
}
});
/* Delete last item function: */
document.getElementById("remove").addEventListener('click', function() {
var els = document.getElementsByTagName("li");
var removeEl = els[els.length - 1]; // <-- fetching last el, If els is an array, it has indices from 0 to els.length - 1. 0 is the first, els.length - 1 is the last index.
var containerEl = removeEl.parentNode;
containerEl.removeChild(removeEl);
});
Use style like $('li.liEl').css('text-decoration','line-through');
Your jQuery css function is wrong, you need to provide two parameter to set css value (see this: css-property-name-value).
Your selector syntax ($('li.liEl')) is not right, it would return all <li> element, not the one the clicked button is located.
You can use this: $(this).parent().css('text-decoration', 'line-through');.
Your code contain some bug, the last added button would not trigger the function. It is because your click function is added before the new element added to DOM. And it would cause your click function to be triggered multiple time for earlier added button.
Here's the snippet for fixed code. Since you already using jQuery, I change several native java script native element query and event handler whith jquery syntax.
$(function () {
$("#add").click(function(evt) {
var input = $('#input').val();
var check = $('<button class="checked">Check</button>');
var newEl = $('<li class="liEl"></li>');
newEl.append(input);
newEl.append(check);
$(check).click(function(evt) {
$(this).parent().css('text-decoration', 'line-through');
});
$('#list').append(newEl);
$('#input').val('');
});
$('#remove').click(function(evt) {
var lastEl = $('li.liEl').last();
lastEl.remove();
});
$('#input').keypress(function(evt) {
if (evt.keyCode === 13) {
$("#add").click();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<body>
<h1> Shopping List </h1>
<button id="add"> Add </button>
<input type="text" id="input" placeholder="Enter Items" />
<button id="remove"> Remove Last </button>
<ul id="list"></ul>
</body>

Categories

Resources