My ‘listmaker’ contains one text box & two buttons. You type an item into the text box, hit “Add Item” and the item is pushed to an array. When you’re done, hit finish and a div is populated with a list of your items. Each list item also has a checkbox. I want to remove any list item with a checked checkbox, preferrably by clicking another button to “remove checked items”, but not necessary.
Here’s the html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<script src='script.js'></script>
<title>Listmaker</title>
</head>
<body>
<form>
<input type="text" id="add" />
<button type="button" name="addItem" id="addItem">Add Item</button>
<button type="button" name="finish" id="finish">Finish</button>
</form>
<div>
<ol id="list">
</ol>
<button type="button" name="lineThrough" id="lineThrough">Remove Checked Items</button>
</div>
</body>
</html>
And the jQuery:
$(document).ready(function() {
var list = [];
$('#add').focus();
$('#addItem').click(function() {
list.push($('#add').val());
$('#add').val('');
$('#add').focus();
});
$('#finish').click(function() {
for(i=0; i<list.length; i++) {
$('#list').append('<li><input type="checkbox" class="unchecked"/>' +list[i]+ '</li>');
}
});
});
I’ve tried it a bunch of different ways over the last few hours, and I don’t even think I was on the right track so I didn’t include my attempt(s) in the code above. I can’t wrap my head around how to iterate over the checkboxes and array.remove() the array item of which it’s a part. Any help would be much appreciated.
DEMO: http://jsfiddle.net/GKnHG/1/
We can use the
.splice()method.I moved the list build to another function (
buildList()), as we call on it when the finish button is clicked, and at the end of the above block.Basically, we’re looping through
each()of theli‘s, then checkingifthey have a:checkedinputinside them (length would be0if there are none).Once we know we’ve got a
liwith a checked checkbox, we can get use.html()to get a string out of thespanelement, and do ajQuery.inArray()check, which returns the index of the value in the array, or-1if it can’t find any.ifit’s greater than or equal to zero, we use thesplice()method to delete the array item at that index. The second argument is how many items to delete.