I'm currently working on an application that counts the number of books as well as putting the book numbers from lowest to greatest. I have a user input box and I'm trying to figure out how to clear it after the user puts a book number in. I've tried $('#input').val(' '); However, this doesn't allow me to put in numbers of two digits like "23".
My Code:
// global variables
var array = new Array();
$(document).ready(function() {
// on enter submit values
$(document).on('keypress', function(e) {
if (e.which == 13) {
// grabs user's input
var $input = $('#input').val();
// stores in the array and sorts from lowest to highest
array.push(parseInt($input));
array.sort(function(a, b) {
return a - b
});
// displays user's inputs
$('#output').text(array.join(", "));
}
// to prevent refresh on enter for forms
$(function() {
$("form").submit(function() {
return false;
});
});
// display values in js console
console.log(array);
// counter for number of books
$('#numOfBooks').text(array.length);
// clears input field
// $('#input').prop("selected", false);
});
// on click submit values
$('#btn').on('click', function() {
// grabs user's input
var $input = $('#input').val();
// stores in the array and sorts from lowest to highest
array.push(parseInt($input));
array.sort(function(a, b) {
return a - b
});
// displays user's inputs
$('#output').text(array.join(", "));
// display values in js console
console.log(array);
// counter for number of books
$('#numOfBooks').text(array.length);
// clears input field
// $('#input').prop("selected", false);
});
// reset
$("#resetButton").on("click", function() {
setTimeout(function() {
location.reload();
}, 300);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="header"> Sort Your Books </h1>
<form id="wrapper">
<span> Enter Book Numbers: </span> <input type="text" id="input" placeholder="Enter a Number...">
<input type="button" id="btn" value="Enter">
</form>
<div class="flex_NumOfBooks">
<h2 id="header_NumOfBooks"> Number of Books: </h2>
<div id="numOfBooks"> </div>
</div>
<div id="wrapper1">
<h2 id="header-books"> Book Numbers: </h2>
<div id="output"></div>
</div>
<button id="resetButton"> Reset </button>
please don't use jq. :)
<!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>App</title>
</head>
<body>
<div class="userGetBookID">
<div class="inputGroup">
<label>Input book id:</label>
<input type="text" class="bookID" placeholder="e.g. esbn-123-abfgd">
<input type="button" class="addBookByID" value="add">
</div>
</div>
<div class="books">
<div class="listGroup">
<p class="books__list-header">list:</p>
<div class="books__list"></div>
</div>
<div class="amountGroup">
<p class="books__amount-header"> amount: </p>
<p class="books__amount"> 0 </p>
</div>
<button class="listReset"> reset </button>
</div>
<script>
const userInput = document.querySelector('.bookID')
const userList = document.querySelector('.books__list')
const userSubmit = document.querySelector('.addBookByID')
const userReset = document.querySelector('.listReset')
const userListAmount = document.querySelector('.books__amount')
const getUserInput = () => userInput.value
const getUserList = () => userList.innerText.split(', ')
const resetUserInput = () => userInput.value = ""
const resetUserList = () => userList.innerText = ""
const addToUserList = (value) => getUserList()[0] == ""
? userList.innerText += value
: userList.innerText += (', ' + value)
const getUserListLength = () => getUserList()[0] == ""
? 0
: getUserList().length
const updateUserListAmount = () => userListAmount.innerText = getUserListLength()
userSubmit.addEventListener('click', (event) => {
addToUserList(getUserInput())
resetUserInput()
updateUserListAmount()
event.preventDefault()
})
userReset.addEventListener('click', (event) => {
resetUserList()
updateUserListAmount()
})
</script>
</body>
</html>
Related
e.g. if a user submits "tacos" twice, instead of having two lines, each containing "tacos", I want to have one line with "tacos x 2". Question 2 - is it possible to create a variable that selects every item in an array except another variable? e.g.
for (let i = 0; i < items.length; i++)
{let j = !i;
}
(I am aware the above code is incorrect, I included it only to illustrate my question)
Thank you in advance.
// key function out of context
if (!items.includes(item.text)) {
items.push(item);
} else {
items.item.number =+1
}
//entire html file with script including key function in context
<!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" autocomplete="off">
<input type="text" name="item" placeholder="Item Name" required>
<input type="submit" value="+ Add Item">
</form>
<button type="reset" value="reset"">clear all</button>
<button class="select">Select all</button>
</div>
<script>
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const selectAll = document.querySelector('.select');
const items = [];
const mySet = new Set();
const userInput = document.querySelector('[type="text"]');
// add items to list
// populate list with html
function add(e) {
e.preventDefault();
console.dir(e.currentTarget)
const text = e.currentTarget.item.value;
const item = {
text,
done:false,
number: 1,
};
console.dir(item)
if (!items.includes(item.text)) {
items.push(item);
} else {
items.item.number =+1
}
e.currentTarget.reset();
itemsList.dispatchEvent(new CustomEvent('itemsUpdated'))
}
function displayItems(item, i) {
const html = items.map((item, i) => `
<li>
<input type="checkbox">
<label name="${item}" id="${i}"><strong>${item.text}</strong> x${item.number} </label>
</li>`).join('');
itemsList.innerHTML = html;
};
addItems.addEventListener('submit', add)
itemsList.addEventListener('itemsUpdated', displayItems)
</script>
</body>
</html>
The problem lies with how you're checking if your item object is in the items array.
Since the elements of your array are objects, you would need to modify that checkup - includes and indexOf won't work.
What you would need to do is:
let indx = items.findIndex(element => element.text === item.text);
array.findIndex will let you find an element within an array which satisfies the given condition. In this case, you want to find a specific product by name. That's why we're doing the element.text === item.text comparison.
Check the updated example below, to see it in action.
const addItems = document.querySelector('.add-items');
const itemsList = document.querySelector('.plates');
const selectAll = document.querySelector('.select');
const items = [];
const mySet = new Set();
const userInput = document.querySelector('[type="text"]');
// add items to list
// populate list with html
function add(e) {
e.preventDefault();
const text = e.currentTarget.item.value;
const item = {
text,
done:false,
number: 1,
};
/* these are the key changes */
let indx = items.findIndex(element => element.text === item.text);
if (indx < 0) {
items.push(item);
} else {
items[indx].number += 1;
}
/* */
e.currentTarget.reset();
itemsList.dispatchEvent(new CustomEvent('itemsUpdated'))
}
function displayItems(item, i) {
const html = items.map((item, i) => `
<li>
<input type="checkbox">
<label name="${item}" id="${i}"><strong>${item.text}</strong> x${item.number}</label>
</li>
`).join('');
itemsList.innerHTML = html;
};
addItems.addEventListener('submit', add)
itemsList.addEventListener('itemsUpdated', displayItems)
<!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" autocomplete="off">
<input type="text" name="item" placeholder="Item Name" required>
<input type="submit" value="+ Add Item">
</form>
<button type="reset" value="reset">clear all</button>
<button class="select">Select all</button>
</div>
</body>
</html>
EDIT There were also minor syntax error edits:
in your original code, your reset button had this as its value - value="reset"". I've removed the extra quote.
your initial incrementing of item.number was also erroneous - instead of items.item.number =+1 it should have been (as it is now) items[indx].number += 1. Note that it's += and not =+.
I want to save the value of a week Input in a Variable.
Additionally, I want to output it in a span.
I tried this:
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
var kw = document.getElementById("week-selector").value;
document.getElementById("kalenderwoche").innerHTML = kw;
Your code works. You just need an event handler
Here I made one that can be reused on load in case the selector has a value already
window.addEventListener("DOMContentLoaded", () => { // when page has loaded
const kw = document.getElementById("kalenderwoche");
const ws = document.getElementById("week-selector");
let kwValue; // you wanted to save it for later?
const setValue = () => kwValue = kw.textContent = ws.value || "";
ws.addEventListener("input", setValue)
setValue(); // initialise
console.log(kwValue); // saved value
});
<input type="week" name="week" id="week-selector" value="2022-W50" />
<span id="kalenderwoche"></span>
you have to add eventListener to week input
var kw = document.getElementById("week-selector")
kw.addEventListener('change', (e) => {
console.log("e=>>>>", e.target)
document.getElementById("kalenderwoche").innerHTML = e.target.value;
})
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
<!DOCTYPE html>
<html>
<body>
<input type="week" name="week" id="week-selector">
<span id="kalenderwoche"></span>
<script>
document.getElementById("week-selector").addEventListener('change', function() {
document.getElementById("kalenderwoche").innerHTML = this.value
})
</script>
</body>
</html>
So I'm currently working on a traveling website-> Link to Deployed Website The website basically allows users to fill out a form with three inputs:
The city they plan on traveling to
The start date of their time in the city
The end date of their time in the city
When the user fills out all the input fields in the form and submits it, the page loads and spits out a list of events happening in the city and a list of breweries close by, all by use of two different APIs.
The page works perfectly fine, but right now I'm trying to figure out how to use local storage to get it to save the last text input. I want the user to see their last city text input in case they accidently refresh the page or close the window. I know this might be a dumb question, but I've been stuck on this for a few hours and feel like an idiot for not knowing how to fix it. I would appreciate it if anyone could help me out. Please don't leave snarky comments, I already feel stupid.
This is the code I'm working stuck on at the moment:
//Input History for the City that the user types
let rememberCity=document.querySelector('.city-text').value
console.log(rememberCity);
//When form is submitted, storage will save the city
form.addEventListener("click", () => {
localStorage.setItem("name",rememberCity);
cityNameDisplay();
});
function cityNameDisplay () {
localStorage.getItem("name");
}
document.body.onload = cityNameDisplay;
Below are the full Javascript + HTML code
const modalClose = document.querySelector(".modal-close");
const modalOpen = document.querySelector(".modal-open");
const form = document.querySelector(".travel-form");
const modalContainer = document.querySelector(".modal");
const modal = document.querySelector(".modal-content");
const cityInput = document.querySelector(".city-text");
const startDate = document.querySelector(".start-date");
const endDate = document.querySelector(".end-date");
const cityError = document.querySelector(".city-error");
const startError = document.querySelector(".start-error");
const endError = document.querySelector(".end-error");
const weatherKey = "c3092c2d4eb3d6f6f64456f5fc464ffa";
// creating an array of all the datepickers in DOM
const datePickers = Array.from(document.querySelectorAll(".date"));
// finding local date
function dateToString(date) {
let year = date.year;
let month = date.month.toString();
let day = date.day.toString();
// padding day and month if necessary for final string
if (day.length === 1) {
day = day.padStart(2, "0");
}
if (month.length === 1) {
month = month.padStart(2, "0");
}
const minDate = `${year}-${month}-${day}`;
return minDate;
}
function datePickerSetUp() {
const minDate = dateToString(luxon.DateTime.now().toObject());
// setting min attribute of datepickers to disable dates in the past
datePickers.forEach((date) => {
date.setAttribute("min", minDate);
});
}
function getCoords(city, start, end) {
const queryCity = city;
fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${queryCity}&appid=${weatherKey}&units=imperial`
)
.then((response) => {
if (response.ok === false) {
cityInput.classList.add("is-danger");
cityError.textContent = "Not a city!";
throw Error("Not a city!");
} else {
response.json().then((data) => {
modalContainer.classList.remove("is-active");
console.log(data.name, data.coord.lat, data.coord.lon);
getEvents(data.coord.lat, data.coord.lon, start, end);
listBreweries(city);
});
}
})
.catch((err) => {
console.log(err.message);
});
}
function handleSubmit() {
const city = cityInput.value.trim().toLowerCase();
let start = luxon.DateTime.fromFormat(startDate.value, "yyyy-MM-dd");
let end = luxon.DateTime.fromFormat(endDate.value, "yyyy-MM-dd");
// if no text in city
if (!city) {
cityInput.classList.add("is-danger");
cityError.textContent = "Choose a city!";
}
if (!startDate.value) {
startDate.classList.add("is-danger");
startError.textContent = "Choose a start date!";
}
if (!endDate.value) {
endDate.classList.add("is-danger");
endError.textContent = "Choose an end date!";
}
if (!city || !startDate.value || !endDate.value) {
modal.classList.add("shake");
var shakeRemove = setTimeout(() => {
modal.classList.remove("shake");
}, 1000);
}
// if all fields are filled
if (city && startDate.value && endDate.value) {
// if the end date is before the start date
if (start > end) {
startDate.classList.add("is-danger");
startError.textContent = "Start date must be after end date!";
endDate.classList.add("is-danger");
endError.textContent = "End date must be before start date!";
return;
}
// convert start and end objects to strings
start = dateToString(start);
end = dateToString(end);
// clear timeout
clearTimeout(shakeRemove);
// send to fetch functions
getCoords(city, start, end);
}
}
// submit listener for form
form.addEventListener("submit", (event) => {
event.preventDefault();
handleSubmit();
});
// If elements have errors and are focused again the error is hidden
cityInput.addEventListener("focus", () => {
if (cityInput.classList.contains("is-danger")) {
cityError.textContent = "";
cityInput.classList.remove("is-danger");
}
});
startDate.addEventListener("focus", () => {
if (startDate.classList.contains("is-danger")) {
startDate.classList.remove("is-danger");
startError.textContent = "";
}
});
endDate.addEventListener("focus", () => {
if (endDate.classList.contains("is-danger")) {
endDate.classList.remove("is-danger");
endError.textContent = "";
}
});
modalClose.addEventListener("click", () => {
modalContainer.classList.remove("is-active");
});
modalOpen.addEventListener("click", () => {
modalContainer.classList.add("is-active");
});
//Input History for the City that the user types
let rememberCity=document.querySelector('.city-text').value
console.log(rememberCity);
//When form is submitted, storage will save the city
form.addEventListener("click", () => {
localStorage.setItem("name",rememberCity);
cityNameDisplay();
});
//City
function cityNameDisplay () {
localStorage.getItem("name");
}
document.body.onload = cityNameDisplay;
datePickerSetUp();
<!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">
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js"
integrity="sha512-Nw0Abk+Ywwk5FzYTxtB70/xJRiCI0S2ORbXI3VBlFpKJ44LM6cW2WxIIolyKEOxOuMI90GIfXdlZRJepu7cczA=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.3/css/bulma.min.css"
integrity="sha512-IgmDkwzs96t4SrChW29No3NXBIBv8baW490zk5aXvhCD8vuZM3yUSkbyTBcXohkySecyzIrUwiF/qV0cuPcL3Q=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="stylesheet" href="assets/css/styles.css">
<title>City Explorer</title>
</head>
<body class="is-fullheight is-clipped">
<div class="container is-justify-content-center">
<!-- MODAL START-->
<div class="modal is-active">
<!-- REMOVE IS ACTIVE CLASS TO WORK ON SITE -->
<div class="modal-background"></div>
<div
class="modal-content column box p-4 is-three-quarters-mobile is-half-tablet is-5-desktop has-background-info-light">
<form class="travel-form is-flex is-flex-direction-column is-align-items-left">
<div class="field">
<label class="label mb-2" for="city">What city are you visiting?</label>
<input class="city-text input" type="text" name="" id="city" autocomplete="off">
<span class="city-error help is-danger"></span>
</div>
<div class="field">
<label class="label mb-2" for="start-date">Start date:</label>
<input class="input date start-date" type="date">
<span class="start-error help is-danger"></span>
</div>
<div class="field">
<label class=" label mb-2" for="end-date">End date:</label>
<input class="date input end-date" type="date">
<span class="end-error help is-danger"></span>
</div>
<button class="modal-button button is-info mt-2" type="submit">Let's Go!</button>
</form>
</div>
<button class="modal-close is-large" aria-label="close"></button>
</div>
<!-- MODAL END-->
<section class="hero is-medium is-link">
<div class="hero-body">
<p class="title has-text-centered">
City Name
</p>
</div>
</div>
</section>
<section class="section pt-6 pb-0 is-medium is-link">
<div class="is-flex is-justify-content-center">
<!--<button class="modal-open button is-centered mb-4 is-info">Chose a new city</button>-->
<button class="modal-open button is-centered mb-4 is-info"><span><img src="assets/images/Map.png" /></span> Chose a new city</button>
</div>
<div class="container">
<div class="columns">
<div class="column">
<div class="notification">
<h1 class="title event-title is-size-4 has-text-centered">Events</h1>
<ul class="event-list">
</ul>
</div>
</div>
<div class="column">
<div class="notification">
<h1 class="title brewery-name is-size-4 has-text-centered">Breweries</h1>
<img src= "assets/images/Beer.png" class="icon" alt="Beer">
<ul class="brewery-list">
</ul>
</div>
</div>
</div>
</div>
</section>
<footer class="is-flex">
<img src="assets/images/skyline.png" alt="skyline">
<img src="assets/images/skyline.png" alt="skyline">
</footer>
<script src="./assets/javascript/modal.js"></script>
<script src="./assets/javascript/Breweries.js"></script>
<script src="./assets/javascript/events.js"></script>
</body>
</html>
Well its sort of simple. You want to pull from local storage and place that data into the default value of the input on page refresh/load. So what you'll want to do is just that.
First you'll need to put the input into local storage. I am just assuming you know about getting input values.
function setLocalInput(input){
localStorage.setItem('savedInput', input);
}
In this case localstorage.setItem takes two parameters, the name you want to set as well as the data you want to set. The input value being passed is the value from your input field that you want saved.
From there you can run a function on page load/refresh that checks the local storage API to see if there is any data, and if so set it as the input default value.
function setInputDefault(){
const storedInput = localStorage.getItem('savedInput');
}
From there you can set storedInput equal to the input default value.
An Edit to my original as I did not fully work through your problem.
So I took your code and went through to refactor a bit. Hopefully my changes aren't too intrusive. I started by taking your ending form.addEventListener("click") funtion and added it into your previously created form.addEventListener("submit") function.
// submit listener for form
form.addEventListener("submit", (event) => {
event.preventDefault();
let rememberCity = document.querySelector(".city-text").value;
localStorage.setItem("name", rememberCity);
handleSubmit();
});
Having rememberCity inside the function allows you to get the form input on submit. Then you store that value locally. From there I created a function which checks to see if you have a saved variable under the name name.
function checkForSaved() {
const savedInput = localStorage.getItem("name");
if (savedInput !== null) {
document.querySelector(".city-text").defaultValue = savedInput;
}
}
After checking local storage it sets the defaultValue of the .city-text element to the contents in local storage. Running your code you also have the longitude and latitude being saved in localstorage as well. I added checkForSaved() just at the bottom of your javascript file, above datePickerSetUp().
Hopefully this helps.
The problem is that you are getting the value of the input at the beginning.
At that point it hasn't got anything in it.
You need to get the value of the input when the user has clicked.
//When form is submitted, storage will save the city
form.addEventListener("click", () => {
//Input History for the City that the user types
let rememberCity=document.querySelector('.city-text').value
console.log(rememberCity);
localStorage.setItem("name",rememberCity);
cityNameDisplay();
});
function cityNameDisplay () {
localStorage.getItem("name");
}
document.body.onload = cityNameDisplay;
I am trying to make a program in javaScript in which I want to update number with current
field.
Suppose the number in the field is 5 and then I enter 4 in textfield then the field is updated
with number 9
document.getElementById('btn').addEventListener('click', () => {
console.log("Button clicked")
var newTotal = 0
var input = parseInt(document.getElementById('text').value)
newTotal = input
if (newTotal) {
console.log(newTotal)
newTotal += input
}
console.log(newTotal)
document.getElementById('textField').innerHTML = newTotal
document.getElementById('text').value = ''
})
<input type="text" id="text">
<h3><span id="textField">0</span></h3>
<input type="submit" id="btn" value="Add Numbers">
Try this brother. You have to assign 0 to the newTotal outside of the function. Because if you put it inside the function, every time the function is called, the newTotal will become 0 and then will add the new input to itself.
Than you.
let newTotal = 0
document.getElementById('btn').addEventListener('click', () => {
const input = parseInt(document.getElementById('text').value)
if (input) {
newTotal += input
}
document.getElementById('textField').innerHTML = newTotal
document.getElementById('text').value = ''
})
<input type="text" id="text">
<h3><span id="textField">0</span></h3>
<input type="submit" id="btn" value="Add Numbers">
document.getElementById('text')
//onchange event to update the value
.addEventListener('change', () => {
//checking if the input is valid integer and alerting
var val = document.getElementById("text").value;
if ( +val !== +val) {
document.getElementById('text').value = '';
alert("Enter valid Number");
throw new Error("Enter valid Number");
}
//if the input in valid integer then adding
document.getElementById("textField").innerHTML =
parseInt(document.getElementById("textField").innerHTML) + parseInt(val);
document.getElementById('text').value = '';
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
</head>
<body>
<input type="text" id="text">
<h3><span id="textField">0</span></h3>
</body>
</html>
Here throwing error and alerting are optional,
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);
});
...
});