input field not resetting - javascript

I'm doing a simple to do app in vanilla JavaScript where I'm trying to reset the input field after every click but for some reason it is not re-setting after every click.
it does reset after you click on the input field, but what I want is for the input field to reset after the clicking the "add" button and not having to click on input field.
the input field is not inside a <form>
this is my function to try to reset the input field
document.getElementById("task").onclick = function() {
Reset();
}
function Reset() {
document.getElementById("task").value = null;
}
<div class="row">
<div class="col s12">
<div class="input-field inline">
<input id="task" type="text">
<label for="email" data-error="wrong" data-success="right">Add a todo</label>
</div>
<a id="add" class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a>
</div>
</div>
this is the problem now for some reason its affecting the localstorage:
function getTodos(){
var todos = new Array();
var todos_str = localStorage.getItem('todo');
if(todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}
// Please do not use inline event handlers, use this instead:
document.getElementById("add").onclick = function() {
Reset();
}
function Reset() {
document.getElementById("task").value = null;
}
function add(){
var task = document.getElementById('task').value;
var todos = getTodos();
todos.push(task);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function remove() {
var id = this.getAttribute('id');
var todos = getTodos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));
show();
return false;
}
function show() {
var todos = getTodos();
var html = '<ul>';
for(var i = 0; i < todos.length; i++) {
html += '<li>' + todos[i] + '<button class="remove" id="' + i + '"> x </button></li>';
};
html += '</ul>';
document.getElementById('todos').innerHTML = html;
var buttons = document.getElementsByClassName('remove');
for( var i = 0; i < buttons.length; i++){
buttons[i].addEventListener('click', remove);
};
}
document.getElementById('add').addEventListener('click', add);
show();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>to do app</title>
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="navbar-fixed">
<nav>
<div class="nav-wrapper">
Logo
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li>Sass</li>
<li>Components</li>
<li>JavaScript</li>
</ul>
</div>
</nav>
</div>
<div class="row">
<div class="col s12">
<div class="input-field inline">
<input class="reset-task" id="task" type="text">
<label for="email" data-error="wrong" data-success="right">Add a todo</label>
</div>
<a id="add" class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a>
</div>
</div>
<div id="todos"></div>
<script src="app.js"></script>
<!--Import jQuery before materialize.js-->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
</body>
</html>

Your example does work but you just used the wrong id.
Use the add id instead of the task id and everything should work fine.
document.getElementById("add").onclick = function() {
Reset();
}
function Reset() {
document.getElementById("task").value = null;
}
<div class="row">
<div class="col s12">
<div class="input-field inline">
<input id="task" type="text">
<label for="email" data-error="wrong" data-success="right">Add a todo</label>
</div>
<a id="add" class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a>
</div>
</div>

Well, it's not clearly where you'd like to get the click event triggered, so I'm assuming that first option is on the body, so:
document.body.addEventListener("click", Rest);
Before your "document.getElementById("task").onclick" should help, there is just a little trick to get this working properly here:
Why is the onclick event on the body element not working?
It's the something if what you like is getting it triggered on element a click event:
document.getElementById("add").onclick = function()......

Related

Local javascript stopped working after including materialize collapsable navbar

So, the JavaScript for my project stopped working after including the materialize JavaScript code needed to make my nav bar turn into a hamburger on mobile devices. I've tried placing my file at the bottom of the html, before the navbar script, and after it. Each time is the same, the hamburger and materialize js works but my js file that I'm using for password validation does not.. Here's my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register Page</title>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Our own style sheet -->
<link rel="stylesheet" href="style.css">
<!-- For icons -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems);
});
</script>
</head>
<body>
<nav>
<div class="nav-wrapper">
Logo
<i class="material-icons">menu</i>
<ul class="right hide-on-med-and-down">
<li>Home</li>
<li>About</li>
<li>Register</li>
<li>Contact</li>
</ul>
</div>
</nav>
<ul class="sidenav" id="mobile-demo">
<li>Home</li>
<li>About</li>
<li>Register</li>
<li>Contact</li>
</ul>
<div class="contact-box">
<div class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<input id="icon_prefix" type="text" class="validate">
<label for="icon_prefix">Full Name</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">email</i>
<input id="icon_prefix" type="email" class="validate">
<label for="icon_prefix">Email</label>
</div>
<div class="input-field col s12">
<i class="material-icons prefix">password</i>
<input id="psw" type="password" name="psw" class="validate" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" required>
<label for="icon_prefix">Password</label>
</div>
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
</div>
</div>
ss3
<div id="message">
<h5>Password must contain the following:</h5>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
<script type="text/javascript" src="validation.js"></script>
</body>
</html>
And here's the validation.js file:
// Script for validating password. This code was authored by w3schools at the url: https://www.w3schools.com/howto/howto_js_password_validation.asp
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");
// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}
// When the user starts to type something inside the password field
myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
// Validate capital letters
var upperCaseLetters = /[A-Z]/g;
if(myInput.value.match(upperCaseLetters)) {
capital.classList.remove("invalid");
capital.classList.add("valid");
} else {
capital.classList.remove("valid");
capital.classList.add("invalid");
}
// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
Am I placing my JavaScript file in the wrong area? I've tried placing it in the body with the same results too. Any help with this would be greatly appreciated :)
Please put your JS file at the end in the <body> tag. like this,
<body>
...
...
<div id="message">
<h5>Password must contain the following:</h5>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
</div>
...
...
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.sidenav');
var instances = M.Sidenav.init(elems);
});
</script>
<!-- my own JavaScript file -->
<script type="text/javascript" src="validation.js"></script>
</body>
And also please use a listener in your file to know that the entire document is first loaded so that your code will get the DOM which it is looking for.
window.addEventListener('load', (event) => {
// Script for validating password. This code was authored by w3schools at the url: https://www.w3schools.com/howto/howto_js_password_validation.asp
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
...
...
});
You can also use DOMContentLoaded if you are not concerned about the stylesheet loading.

What are the methods to limit the number and time of alerts?

when I click on the "Todo Ekleyin" button, I get a warning. However, I would like this alert to appear only once per press, not multiple times, and can be pressed again after the alert disappears. How can I achieve this and?
Thank you in advance for your answer, good work. (If there is a method other than the method you suggested, I would be glad if you can write its name.)
// Tüm Elementleri Seçme
const form = document.querySelector("#todo-form");
const todoInput = document.querySelector("#todo");
const todoList = document.querySelector(".list-group");
const firstCardBody = document.querySelectorAll(".card-body")[0];
const secondCardBody = document.querySelectorAll(".card-body")[1];
const filter = document.querySelector("#filter");
const clearButton = document.querySelector("#clear-todos");
eventListeners();
function eventListeners() { // Tüm Event Listenerlar
form.addEventListener("submit", addTodo);
}
function addTodo(e) {
const newTodo = todoInput.value.trim();
if (newTodo === "") { // Alarm Verme
showAlert("danger","Lütfen Bir Todo Giriniz");
}
else {
addTodoToUI(newTodo);
}
addTodoToUI(newTodo);
e.preventDefault();
}
function showAlert(type,message){
const alert = document.createElement("div");
alert.className = `alert alert-${type}`;
alert.textContent = message;
firstCardBody.appendChild(alert);
//setTimeout
setTimeout(function(){
alert.remove();
}, 1000);
}
function addTodoToUI(newTodo) { // String Değerini List Item olarak Ekleyecek.
// List Item Oluşturma.
const listItem = document.createElement("li");
// Link Oluşturma
const link = document.createElement("a");
link.href = "#";
link.className = "delete-item";
link.innerHTML = "<i class = 'fa fa-remove'></i>";
listItem.className = "list-group-item d-flex justify-content-between";
// Text Node
listItem.appendChild(document.createTextNode(newTodo));
listItem.appendChild(link);
// Todo List'e List Item'ı Ekleme
todoList.appendChild(listItem);
// Ekleme Sonrası Input'tan yazı Silme
todoInput.value = "";
}
// Todo Ekleme Bilgi Mesajı
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />
<title>Todo List</title>
</head>
<body>
<div class="container" style="margin-top: 20px">
<div class="card row">
<div class="card-header">Todo List</div>
<div class="card-body">
<form id="todo-form" name="form">
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="todo" id="todo"
placeholder="Bir Todo Girin" />
</div>
</div>
<button type="submit" class="btn btn-danger">Todo Ekleyin</button>
</form>
<hr />
<!-- <div class="alert alert-danger" role="alert">
This is a danger alert—check it out!
</div> -->
</div>
<div class="card-body">
<hr />
<h5 class="card-title" id="tasks-title">Todolar</h5>
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="filter" id="filter"
placeholder="Bir Todo Arayın" />
</div>
</div>
<hr />
<ul class="list-group">
<!-- <li class="list-group-item d-flex justify-content-between">
Todo 1
<a href = "#" class ="delete-item">
<i class = "fa fa-remove"></i>
</a>
</li>-->
</ul>
<hr />
<a id="clear-todos" class="btn btn-dark" href="#">Tüm Taskları Temizleyin</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous">
</script>
<script src="berkay.js"></script>
</body>
</html>
You can put an integer in your alert function and every using array increase a one more.
For example, if you want after 5 times don't show alert.
var a = 0;
var b = true;
if (newTodo === "" || b) { // Alarm Verme
showAlert("danger","Please Give me a Todo!");
a++;
if(a == 5 ){
b = false;
}
}

Function will not update variable

The variable status is set to "uncheck" and needs to be updated to "done" using the change() function.
Ultimately what needs to happen When button with id randomIdTwo is pressed, The completeTodo() function is called which causes the list item to be removed from its current div "list", appended to the div "complete-list", and the change() function updates the value of the "status" variable from "uncheck" to "done".
Everything works except the change() function.
document.getElementById('button').addEventListener('click', function addTodo() {
var value = document.getElementById('input').value;
var status = "uncheck";
var randomId = Math.random();
var randomIdTwo = Math.random();
function change() {
status = "done";
};
const item = `<li>
<div class="item">
<div class="complete">
<button id="` + randomIdTwo + `" class="${status}"></button>
</div>
<p class="text">${value}</p>
<div class="remove">
<button id="` + randomId + `" class="todo"></button>
</div>
</div>
</li>`;
const position = "beforeend";
list.insertAdjacentHTML(position, item);
document.getElementById(randomId).addEventListener('click', function removeTodo() {
var item = this.closest('li');
item.remove();
});
document.getElementById(randomIdTwo).addEventListener('click', function completeTodo() {
var item = this.closest('li');
item.remove();
document.getElementById("completelist").appendChild(item);
change();
});
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="Resources/CSS/reset.min.css">
<link rel="stylesheet" type="text/css" href="Resources/CSS/style.css">
</head>
<body>
<div class="container">
<header>
<div id="datetime"></div>
<div id="ampm"></div>
<input type="text" id="input" placeholder="Add an item" />
<button id="button" type="button"><img src="./img/additem4.png"></button>
</header>
<div id="list">
</div>
<div id="divline"></div>
<div id="completelist">
</div>
</div>
<script src="resources/JS/app.js"></script>
</body>
</html>
Changing the status variable doesn't change the class of the element. You need to update the button's classList
document.getElementById('button').addEventListener('click', function addTodo() {
var value = document.getElementById('input').value;
var status = "uncheck";
var randomId = Math.random();
var randomIdTwo = Math.random();
function change(button) {
button.classList.add("done");
button.classList.remove("uncheck");
};
const item = `<li>
<div class="item">
<div class="complete">
<button id="` + randomIdTwo + `" class="${status}"></button>
</div>
<p class="text">${value}</p>
<div class="remove">
<button id="` + randomId + `" class="todo"></button>
</div>
</div>
</li>`;
const position = "beforeend";
list.insertAdjacentHTML(position, item);
document.getElementById(randomId).addEventListener('click', function removeTodo() {
var item = this.closest('li');
item.remove();
});
document.getElementById(randomIdTwo).addEventListener('click', function completeTodo() {
var item = this.closest('li');
item.remove();
document.getElementById("completelist").appendChild(item);
change(this);
});
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="Resources/CSS/reset.min.css">
<link rel="stylesheet" type="text/css" href="Resources/CSS/style.css">
</head>
<body>
<div class="container">
<header>
<div id="datetime"></div>
<div id="ampm"></div>
<input type="text" id="input" placeholder="Add an item" />
<button id="button" type="button"><img src="./img/additem4.png"></button>
</header>
<div id="list">
</div>
<div id="divline"></div>
<div id="completelist">
</div>
</div>
<script src="resources/JS/app.js"></script>
</body>
</html>
You're using string interpolation to set the class initially, but string interpolation does not create a data-binding between the resultant element and the variable. So change() is being called, and status is being updated, but the value of the element you created via a string isn't seeing that change, so it's not being updated.
You would need to access the element in the DOM and change it's classList manually.

How do I remove a to do list item after it is added

I really tried everything, almost every function in JS. But I cannot remove the list item from the to-do list once it is added. I have tried adding event listeners, onclick=" " etc but nothing works. Can someone please look at my code and tell me what I am doing wrong. Thank You, any help is much appreciated.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="script.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet href="style.css">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<meta charset="UTF-8">
<title>To-Do-List</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
</div>
</div>
<script>
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event){
const element = event.target;
if(element.type === "close"){
delete element;
}
}
</script>
</body>
</html>
JS:
$(document).ready(function(){
document.getElementById('addTask').addEventListener("click", function(){
var task = document.getElementById('task').value;
if(task == ""){
alert("You Must Enter A Value!");
}else{
document.getElementById('myUL').innerHTML += '<li>' + task + '</li>' + '<button class="close" >&#10007</button>' + '<br><br>' + '<button class="check" >✓</button>' + '<br><br>';
}
var button = document.querySelectorAll('.close');
for(var i = 0; i < button.length;i++){
button[i].addEventListener("click", function(){
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
});
}
var check = document.querySelectorAll('.check');
for(var i = 0; i < check.length;i++){
check[i].addEventListener("click", function(){
this.parentNode.style.textDecoration = "line-through";
});
}
});
});
Don't try to concatenate innerHTML strings when you have listeners attached to elements inside, else the listeners will be lost. Instead, append elements properly with appendChild.
delete element won't actually do anything, because element is a variable, not a property of an object - try using .remove() instead, to remove the li (and put the button inside the li so that the HTML is valid).
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event) {
const element = event.target;
if (element.className === "close") {
element.parentElement.remove();
}
}
document.getElementById('addTask').addEventListener("click", function() {
var task = document.getElementById('task').value;
if (task === "") return alert("You Must Enter A Value!");
const li = list.appendChild(document.createElement('li'));
li.textContent = task;
const button = li.appendChild(document.createElement('button'));
button.className = 'close';
button.textContent = '✗';
});
.close {
position: absolute;
left: 150px;
}
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
Your .querySelectorAll() simply needs to target .close rather than close. In addition to this, you'll probably want to target the close button's parent (the item itself), with .parentNode. Note that you probably don't want to hide it, but rather actually simply remove both the <li> and the close icon, so that you can add more items after removal of the item(s). This can be done with:
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
And can be seen working in the following:
var list = document.getElementById('myUL');
list.addEventListener("click", boxChecked);
function boxChecked(event) {
const element = event.target;
if (element.type === "close") {
delete element;
}
}
$(document).ready(function() {
document.getElementById('addTask').addEventListener("click", function() {
var task = document.getElementById('task').value;
if (task == "") {
alert("You Must Enter A Value!");
} else {
document.getElementById('myUL').innerHTML += '<li>' + task + '</li>' + '<button class="close" >&#10007</button>' + '<br><br>';
}
var button = document.querySelectorAll('.close');
for (var i = 0; i < button.length; i++) {
button[i].addEventListener("click", function() {
this.parentNode.removeChild(this.previousSibling);
this.parentNode.removeChild(this);
});
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script src="script.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<meta charset="UTF-8">
<title>To-Do-List</title>
</head>
<body>
<div class="container">
<div id="header">
<h1>My To Do List</h1>
</div>
<form autocomplete="off">
<input type="text" id="task" placeholder="Title...">
</form>
<button id="addTask">Add</button>
</div>
<br><br>
<div id="tasks">
<ul id="myUL">
</ul>
</div>
</body>
</html>
Also note that your stylesheet is missing a closing ", and you have two additional closing </div> that don't match anything in your above code.

Remove last item jquery

On click of a button, result appends to another div with the total increasing on each click.
When Remove Last button is clicked it removes the appended div but does not adjust the total.
I've looked all over for a function with no luck.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Remove last</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body onLoad="renderTime();">
<div class="container-fluid">
<div class="row">
<div class="col-xs-4" id="printarea" >
<div id="print-container">
<div class="item"></div>
<div class="total"></div>
</div>
</div>
<div class="col-xs-8">
<ul class="final">
<li class="remove"><input type="submit" value="Remove Last" class="print-btn remove-item"></li>
<li class="remove"><input type="submit" value="Remove All" class="print-btn" data-corners="false" id="submit" onclick="refresh()"></li>
</ul>
<hr />
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="content">
<ul class="sub-menu">
<li><button class="menu item1">Item 1</button></li>
<li><button class="menu item2">Item 2</button></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
//add item
$('.item1').click(function(){
$('<div class="delete">Item 1 - <span class="skill"> 840</span></div><br />').appendTo('.item');
counter();
});
$('.item2').click(function(){
$('<div class="delete">Item 2 - <span class="skill"> 910</span></div><br />').appendTo('.item');
counter();
});
//remove last item
$('.remove-item').click(function(){
$(".delete:last").remove();
});
</script>
<script type="text/javascript">
function refresh() {
setTimeout(function () {
location.reload()
}, 100);
}
</script>
<script type="text/javascript">
var counter = function() {
var total = 0;
$(".skill").each(function() {
total += +$(this).text();
});
$('.total').text('Total: ' + total);
};
</script>
</body>
</html>
You need to call counter(); method after the element is removed.
//remove last item
$('.remove-item').click(function() {
$(".delete:last").remove();
counter();
});
That is because you have not called counter function after removing element. you need to call it in remove item clicked handler:
$('.remove-item').click(function(){
$(".delete:last").remove();
counter();
});
You should also parse the values while getting the text before calculating total:
var total = 0;
$(".skill").each(function() {
total += + parseInt($(this).text() , 10);
});
$('.total').text('Total: ' + total);

Categories

Resources