Removing Items Stored in Local Memory With Checked Boxes Jquery - javascript

I have items being stored in an array then the array stored in local memory.
i am printing out the items to the screen for the users to see with check boxes attached to each item.
I allow the user to clear all of the items in the localStorage like this,
$('#clear').click( function() {
window.localStorage.clear();
location.reload();
return false;
});
I want to allow the user to clear any one check boxed item they want. How can I implement a function to remove the selected check boxed item from the array.
$(document).ready(function () {
localArray = [];
loadKeyWords();
function loadKeyWords() {
$('#keyWords').html('');
localArray = JSON.parse(localStorage.getItem('keyWords'));
for(var i = 0; i < localArray.length; i++) {
$('#keyWords').prepend('<li><input id="check" name="check" type="checkbox">'+localArray[i]+'</li>');
}
}
$('#add').click( function() {
var Description = $('#description').val();
if($("#description").val() === '') {
$('#alert').html("<strong>Warning!</strong> You left the to-do empty");
$('#alert').fadeIn().delay(1000).fadeOut();
return false;
}
$('#form')[0].reset();
var keyWords = $('#keyWords').html();
localArray.push(Description);
localStorage.setItem('keyWords', JSON.stringify(localArray));
loadKeyWords();
return false;
});
if(localStorage.getItem('keyWords')) {
$('#keyWords').JSON.parse(localStorage.getItem('keyWords'));
}
$('#clear').click( function() {
window.localStorage.clear();
location.reload();
return false;
});
$('#clearChecked').click( function() {
if ($(this).is(':unchecked')) {
localArray.push($(this).val());
}
else {
if ((index = localArray.indexOf($(this).val())) !== -1) {
localArray.splice(index, 1);
}
$('#form')[0].reset();
var keyWords = $('#keyWords').html();
localArray.push(Description);
localStorage.setItem('keyWords', JSON.stringify(localArray));
loadKeyWords();
window.location.reload();
return false;
}
});
}); // End of document ready function
My HTML
<!doctype html>
<html>
<head>
<title>Wuno Zensorship</title>
<script src="jquery-1.11.3.min.js"></script>
<script src="popup.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<img src="icon48.png">
<section>
<form id="form" action="#" method="POST">
<input id="description" name="description" type="text" />
<input id="add" type="submit" value="Add" />
<button id="clearChecked">Clear Checked Items</button>
<button id="clear">Clear All</button>
</form>
<div id="alert"></div>
<ul id="keyWords"></ul>
</body>
</html>

You should iterate over the ul looking for the li elements whosecheckbox are checked, then remove them from localArray. Try this:
$('#clearChecked').click( function() {
$('#keyWords > li > input:checked').each(function(){
var desc = $(this).parent().text();
var index = localArray.indexOf(desc);
localArray.splice(index, 1);
});
...
});

Related

Created a delete function for a list, but not all checked items are deleting

I am currently taking Wes Boros JS 30 challenge and for this particular class, we created a list where we add foods we like. As an extra assignment, we are to create a select all function, an unselect all function, and a delete function. I was able to successfully create a select all function where once you click that button, it selects all the items on the current list. My issue is that the delete function I created deletes everything, except for one or two items. Those undeleted items still remain checked, but I have to click on the delete button again in order for it to delete. FYI: I local storage was incorporated in this exercise.
Can somebody help me out and also explain what I was doing wrong?
Here is a jsfiddle of it as well
Here is how I have my HTML set up:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LocalStorage</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper">
<h2>LOCAL TAPAS</h2>
<p></p>
<ul class="plates">
<li>Loading Tapas...</li>
</ul>
<form class="add-items">
<input type="text" name="item" placeholder="Item Name" required>
<input type="submit" value="+ Add Item">
</form>
<input type="button" onclick="selectAll()" value="Select All"/>
<input type="button" onclick="UnSelectAll()" value="Unselect All"/>
<input type="button" onclick="deleteItem()" value="delete Item"/>
</div>
</body>
</html>
Here is my Javascript:
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const items = JSON.parse(localStorage.getItem('items')) || [];
//DELETE FUNCTION
function deleteItem(){
var boxes = document.getElementsByClassName('chk');
var texts = document.getElementsByClassName('txt');
for(var i = 0; i < boxes.length; i++){
box = boxes[i];
txt = texts[i];
if(box.checked){
box.parentNode.removeChild(box);
txt.parentNode.removeChild(txt);
}
}
}
//SELECT ALL FUNCTION
function selectAll(){
var checkedItem = document.getElementsByName('item');
for (var i = 0; i < checkedItem.length; i++) {
if (checkedItem[i].type == 'checkbox')
checkedItem[i].checked = true;
}
}
//UNSELECT ALL FUNCTION
function UnSelectAll(){
var checkedItem = document.getElementsByName('item');
for (var i = 0; i < checkedItem.length; i++) {
if (checkedItem[i].type == 'checkbox')
checkedItem[i].checked = false;
}
}
//ADD ITEM FUNCTIO
function addItem(e){
e.preventDefault()
const text = (this.querySelector('[name=item]')).value;
const item = {
text,
done: false
};
items.push(item);
populateList(items, itemsList);
localStorage.setItem('items', JSON.stringify(items));
this.reset();
}
//DISPLAY THE HTML FUNCTION
function populateList(plates =[], platesList) {
platesList.innerHTML = plates.map((plate, i) => {
return `
<li>
<input class="chk" type="checkbox" name="item" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} />
<label class="txt" name="item" for="item${i}">${plate.text}</label>
</li>
`
}).join('');
}
function toggleDone(e){
if(!e.target.matches('input')) return;
const el = e.target;
const index = el.dataset.index;
items[index].done = !items[index].done;
localStorage.setItem('items', JSON.stringify(items));
populateList(items, itemsList);
}
addItems.addEventListener('submit', addItem)
itemsList.addEventListener('click', toggleDone)
populateList(items, itemsList);
//DELETE ITEM EVENT HANDLER
itemsList.addEventListener('click', deleteItem);
The reason why your delete function wasn't working properly it's because Node.childNodes returns a live NodeList which means when you use removeChild on each element in the collection the other elements gets rearranged and the length of list get's smaller causing you to skip some of them so you should convert your html collection to an array using Array.from
function deleteItem(){
var boxes = document.getElementsByClassName('chk');
var texts = document.getElementsByClassName('txt');
arrbox = Array.from(boxes)
arrtext = Array.from(texts)
for(var i = 0; i < arrbox.length; i++){
var box = arrbox[i];
var txt = arrtext[i];
if(box.checked){
box.parentNode.removeChild(box);
txt.parentNode.removeChild(txt);
}
}
}
Here is working jsfiddle

Local storage example doesn't work how I expect it to be

In my Web university course there is this example with local storage and it says it should show in the input area the number of clicks on the button and also store it in localstorage, but all I get is NaN on the input no matter how many times I click on the button.
<head>
<script>
window.onload = function()
{
var el=document.getElementById("bt");
el.onclick= function()
{
var x = parseInt(localStorage.getItem("nrc"));
if (x!==NaN){
localStorage.setItem("nrc", x + 1);
}
else{
localStorage.setItem("nrc", "1");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
document.getElementById("write").value = localStorage.getItem("nrc");
var buton2=document.getElementById("bt2");
buton2.onlick = function ()
{
localStorage.removeItem("nrc");
}
}
</script>
</head>
<body>
<p> Number of clicks on the button <input type="text" id="write" value="0"> </p>
<button id="bt"> Click</button>
<button id="bt2"> Click2</button>
</body>
Edit: problem was solved, but now if i want to remove an item from local storage or clear the localstorage it doesn't work.
You have a typo, you wrote onlick instead of onclick
buton2.onclick = function() {
console.log('clearing storage!');
localStorage.removeItem("nrc");
// Reset input back to zero
document.getElementById("write").value = '0';
}
Complete working example here
You were checking a non number to a non number which will always true.
Anyways the solution is already posted in the comments
<head>
<script>
window.onload = function() {
var el = document.getElementById("bt");
el.onclick = function() {
var x = parseInt(localStorage.getItem("nrc"));
if (!isNaN(x)) {
localStorage.setItem("nrc", x + 1);
} else {
localStorage.setItem("nrc", "1");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
document.getElementById("write").value = localStorage.getItem("nrc");
}
</script>
</head>
<body>
<p> Number of clicks on the button <input type="text" id="write" value="0"> </p>
<button id="bt"> Click</button>
</body>

If condition not working in form validation

This is a question from my elder brother's question paper which I'm trying to solve but I am not able to do so .
Create a form containing a two Text fields and radio button and submit button. Name the
text fields account number and amount and radio button as transaction (deposit ,withdraw
and enquiry).Write a JavaScript the validates the text field to have only numbers, the first
text field should be of size 10 and second text field should have values between 500 to
20,000. Using onclick event a jQuery is called that performs necessary transactions and
display the updated value.
.............................................................................
So I have written the following code:
form1.html
<!DOCTYPE html>
<html>
<head>
<title>Web Tech DA 1</title>
<script type="text/javascript" src="script1.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#sub').click(function() {
var acc=document.getElementById("acc").value;
var amt=document.getElementById("amt").value;
var bal=acc%100;//balance , I am using this to dynamically generate a new balance each time a new account number is entered
$("#t1").click(function(){
bal=acc+amt;
alert(bal);
});
$("#t2").click(function(){
if(acc>amt){
bal=acc-amt;
alert(bal);
}
else{
alert('Insufficient Funds.');
}
});
$("#t3").click(function(){
alert(bal);
});
});
});
</script>
</head>
<body>
<form name="myform" onsubmit="if(validateform()) {window.alert('succefully submitted')} else {return false;}" >
<p>Account Number : <input type="text" maxlength="10" name="acc" id="acc" height="20px" width="100px" required="required" onblur="validacc(this.value)"></p>
<p>Amount : <input type="text" name="amt" id="amt" height="20px" width="100px" required="required" onblur="validamt(this.value)"></p>
<p>Transaction : <input type="radio" name="trans" id="t1" value="deposit" />Deposit
<input type="radio" name="trans" id="t2" value="withdraw" />Withdraw
<input type="radio" name="trans" id="t3" value="enquiry" />Enquiry </p>
<input type="submit" name="sub" id="sub" value="Submit">
</form>
</body>
main1.css
*{
margin:0;
padding: 0;
}
body{
margin: 25px;
}
form p {
margin: 10px;
}
form input {
margin: 10px;
}
script1.js
function validateform() {
var acc = document.getElementById("acc").value.trim();
var amt = document.getElementById("amt").value.trim();
if(validregno(acc)&&validname(amt))
{window.alert("No errors found");return true;}
else
{window.alert("invalid entries found");return false;}
}
// Overall Go
function validacc(r)
{
var p = new RegExp(/^[0-9]{10}$/i);
if(!p.test(r))
{
chngborder("acc");
return false;
}
chngborderr("acc");
return true;
}
function validamt(amt)
{
var p = new RegExp( /^[0-9]{1,}$/);
if(amt>=500 && amt<=20000){
if(p.test(n))
{
chngborderr("amt");
return false;
}
else
{
chngborder("amt");
return true;
}
}
chngborder("amt");
return false;
}
function chngborder(i)
{
document.getElementById(i).style.borderColor="red";
}//red color means wrong format
function chngborderr(i)
{
document.getElementById(i).style.borderColor="green";
}//green color means correct format
For some reason I'm not able to enter a number in the "Amount" text field and none of the radio buttons are working .
Please point out any mistakes that I have done here .
P.S. I'm new to jQuery and form validation
UPDATE
I made the changes pointed out and even then for some reason the "Amount" text field doesn't get validated and the "submit" button resets the form .
I am analysing your code. if this is exactly what you have, I can notice that
1 - You did not include jQuery library in the of you.
you can do it by adding <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> or <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script> inside the <head> element
2 - I think it is better to add and Else in onsubmit event of #myForm
if(validateform()) window.alert('succefully submitted'); else return false.
3 - I have never seen a javascript (.js files) variable declaration starting by int: they start with var keyword regardless the type of the variable
Here is a working code.
script1.js
function validateform() {
var accValue = document.getElementById("acc").value.trim();
var amtValue = document.getElementById("amt").value.trim();
if (validacc(accValue) && validamt(amtValue))
{ window.alert("No errors found"); return true; }
else
{ window.alert("invalid entries found"); return false; }
}
// Overall Go
function validacc(r) {
var p = new RegExp(/^[0-9]{10}$/i);
if (!p.test(r)) {
chngborder("acc");
return false;
}
chngborderr("acc");
return true;
}
function validamt(amt) {
var p = new RegExp(/^[0-9]{1,}$/);
var amtValue = document.getElementById("amt").value;
if (amtValue >= 500 && amtValue <= 20000) {
if (p.test(n)) {
chngborderr("amt");
return false;
}
else {
chngborder("amt");
return true;
}
}
chngborder("amt");
return false;
}
function chngborder(i) {
document.getElementById(i).style.borderColor = "red";
}//red color means wrong format
function chngborderr(i) {
document.getElementById(i).style.borderColor = "green";
}
//Script inside your html file
$(document).ready(function () {
$('#sub').click(function() {
var accValue = document.getElementById("acc").value;
var amtValue = document.getElementById("amt").value;
var bal = accd % 100;})
$("#t1").click(function(){
bal = Number(document.getElementById("aac").value) +
Number(document.getElementById("amt").value);
alert(bal);
});
$("#t2").click(function(){
if(acc > amt){
Number(document.getElementById("aac").value) +
Number(document.getElementById("amt").value);
alert(bal);
}
else{
alert('Insufficient Funds.');
}
});
});

How to delete an appended message in jquery after you have already appended once clicking the same button?

I have looked through a lot of the already asked questions and cannot find it. I need the previous appended message to be deleted once you hit the submit button again. So this will let you choose your character that you type into the input field and then it will append a message bellow telling you that you choose x character. After that you can resubmit another character which I want, but I do not want the previous append to be there.
I tried to do a search function in javascript and if it was not equal to -1 then delete the first p in the div, but that did not work=/
Thanks for your help in advance.
html:
<!DOCTYPE html>
<html>
<head>
<title>Result</title>
<link rel='stylesheet' type='text/css' href='styles/main.css'/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type='text/javascript' src='jquery/script.js'></script>
</head>
<body>
<form class="" action="index.html" method="post">
Chose your character (human, orc, elf) : <br><br><input id='text' type="text" name="mess" value="">
<button id='button1' type="button" name="button" onclick="chooseChar()">Submit</button>
</form>
<br>
<div id="box_holder"></div>
<br><br>
<button id='button2' type='button' name='button2' onclick="redirect()">Start Your Adventure</button>
</body>
</html>
JS:
$(document).ready(function() {
$('#button1').click(function(){
var send = $("input[name=mess]").val();
$('#box_holder').append('<p>'+ 'You have chosen your character to be: '+send+'</p>');
});
$('input').css("color","blue");
});
chooseChar = function () {
var text = document.getElementById('text').value;
var text = text.toLowerCase();
if(text == 'human') {
$(document).ready(function() {
$('#button1').click(function(){
var div = $("#box_holder p").val();
var searchTerm = "You";
var searchDiv = div.search(searchTerm);
if (searchDiv != -1) {
$('div p').first().remove();
}
});
});
window.alert("HUMAN YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'orc') {
window.alert("ORC YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'elf') {
window.alert("ELF YOU ARE !(You may change your character at anytime)");
return;
} else {
window.alert("Start over! Please choose one of the characters above!");
$(document).ready(function(){
$('div').remove();
});
return;
}
$(document).ready(function() {
});
};
redirect = function() {
var text = document.getElementById('text').value;
var url = text+".html";
window.location.href = url;
}
So your variable send gets sent and then it clears out the input field with either of those functions
$(document).ready(function() {
$('#button1').click(function(){
$('#box_holder').children('p').remove(); <===========
or Either of these should work
$('#box_holder').empty(); <===========================
var send = $("input[name=mess]").val();
$('#box_holder').append('<p>'+ 'You have chosen your character to be: '+send+'</p>');
});
$('input').css("color","blue");
});
Instead of using append, try using html as follows
$('#box_holder').html('<p>'+ 'You have chosen your character to be: '+send+'</p>');
Here is a Plunkr to explain it a little better
$(document).ready(function() {
$('#button1').click(function() {
var send = $("input[name=mess]").val();
$('#box_holder').html('<p>' + 'You have chosen your character to be: ' + send + '</p>');
});
$('input').css("color", "blue");
});
chooseChar = function() {
var text = document.getElementById('text').value;
text = text.toLowerCase();
if (text == 'human') {
$(document).ready(function() {
$('#button1').click(function() {
var div = $("#box_holder p").val();
var searchTerm = "You";
var searchDiv = div.search(searchTerm);
if (searchDiv != -1) {
$('div p').first().remove();
}
});
});
window.alert("HUMAN YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'orc') {
window.alert("ORC YOU ARE! (You may change your character at anytime)");
return;
} else if (text == 'elf') {
window.alert("ELF YOU ARE !(You may change your character at anytime)");
return;
} else {
window.alert("Start over! Please choose one of the characters above!");
$(document).ready(function() {
$('div').remove();
});
return;
}
$(document).ready(function() {
});
};
redirect = function() {
var text = document.getElementById('text').value;
var url = text + ".html";
window.location.href = url;
}
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#2.1.4" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<form class="" action="index.html" method="post">
Chose your character (human, orc, elf) :
<br />
<br />
<input id="text" type="text" name="mess" value="" />
<button id="button1" type="button" name="button" onclick="chooseChar()">Submit</button>
</form>
<br />
<div id="box_holder"></div>
<br />
<br />
<button id="button2" type="button" name="button2" onclick="redirect()">Start Your Adventure</button>
</body>
</html>
You have to remember, the append() function appends the content on the selected component. The html() function replaces all content inside of it.
Hope it helps

How to store checkbox and array values (cookies)

I want to save the boolean values of my checkbox for a longer period. Also I need to store the values of each checkbox in an array to read them out later. I´ve tried some example code and tutorials about cookies but nothing seems to work.
With checklist_1s.html i access checklistRequest.js to store the values of each checkbox in my array. Later I´ll need to use this array for another js function in another window, but the moment I open this window, my array is gone.
I´m looking for an easy solution here, if possible.
Note: I know using the same name for every checkbox is an violation, but it seems to work so far and I couldn´t find any other way to get it to work for every checkbox (I´ll need like 200 later)
checklist_1s.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="../../style.css"></link>
<script src="checklistRequest.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="https://raw.github.com/andris9/jStorage/master/jstorage.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<style>
</style>
</head>
<body class="main">
<div class="main_2">
<p>
<h1>Checklist</h1>
<form>
<input type="checkbox" name="remember" id="remember" onclick="checkboxFunction(value, 0)" value="F-Card geholt">F-Card geholt<br>
<input type="checkbox" name="remember" id="remember" onclick="checkboxFunction(value, 1)" value="Ersti Rally">Ersti Rally <br>
<input type="checkbox" name="remember" id="remember" onclick="checkboxFunction(value, 2)" value="TEST">TEST<br>
</form>
<input type="button" name="alert" value="Aktualisieren" onclick="alertFunction()">
<!-- Example Code-->
<script>
$("#checkAll").on("change", function(){
$(':checkbox').not(this).prop('checked', this.checked);
});
$(":checkbox").on("change", function(){
var checkboxValues = {};
$(":checkbox").each(function(){
checkboxValues[this.id] = this.checked;
});
$.cookie('checkboxValues', checkboxValues, { expires: 7, path: '/' })
});
function repopulateCheckboxes(){
var checkboxValues = $.cookie('checkboxValues');
if(checkboxValues){
Object.keys(checkboxValues).forEach(function(element){
var checked = checkboxValues[element];
$("#" + element).prop('checked', checked);
});
}
}
$.cookie.json = true;
repopulateCheckboxes();
</script>
</p>
</div>
</body>
</html>
checklistRequest.js
var checkbox = document.getElementsByName("remember");
var checkboxArray = [];
function checkboxFunction(value, index)
{
if(checkbox[index].checked == true)
{
checkboxArray[index] = value;
}
if (checkbox[index].checked == false && value == checkboxArray[index])
{
checkboxArray[index] = null;
}
}
function alertFunction()
{
for(var i=0; i<99; i++)
{
if (typeof checkboxArray[i] != 'undefined' && checkboxArray[i] != null)
{
alert(checkboxArray[i]);
}
}
alert("TEST");
}

Categories