Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  75] [ 1]  / answers: 1 / hits: 15264  / 11 Years ago, thu, february 6, 2014, 12:00:00

I am trying to remove items in a list when they are checked-off and then the remove button clicked. I think my problem may be in the removeItem function. var x = document.getElementById(items-listed <li>); because when i remove <li> the entire list is removed.



<div>
<div id=center-container>
<h4>Enter an Item for Your Shopping List:</h4>
<hr />
<form name=form>
<label for=item>Item:</label>
<input type=text placeholder=Shopping Items id=item name=itemEntered />
<input type=button value=Enter id=Enter onclick=javascript:addItem(); />
</form>
</div>
</div>

<div>
<div id=items-container>
<h4>Your list of Items:</h4>
<form>
<input type=button value=Remove selected items onclick=javascript:removeItem(); />
</form>
<hr />
<ul id=items-listed>

</ul>
</div>
</div>

function addItem() {
var item = [];
item = document.getElementById('items-listed');
item.innerHTML += <li><input type='checkbox'> + document.form.itemEntered.value + </li>;
}
function removeItem () {
var x = document.getElementById(items-listed <li>);
x.remove();
}

More From » html

 Answers
47

A little help : http://jsfiddle.net/wared/N3m65/.



<div>
<button onclick=add()>add</button>
<button onclick=rem()>rem</button>
</div>
<ul id=list>
<li><input type=checkbox /> item</li>
</ul>


function add() {
var list = document.getElementById('list'),
item = document.createElement('li');
item.innerHTML = '<input type=checkbox /> item';
list.appendChild(item);
}

function rem() {
var list = document.getElementById('list'),
items = Array.prototype.slice.call(list.childNodes),
item;
while (item = items.pop()) {
if (item.firstChild && item.firstChild.checked) {
list.removeChild(item);
}
}
}





Here is a jQuery solution : http://jsfiddle.net/wared/N3m65/.



function jAdd() {
$('#list').append('<li><input type=checkbox /> item</li>');
}

function jRem() {
$('#list').children().filter(function () {
return this.firstChild.checked;
}).remove();
}


As BlackSheep suggested, you could also do this :



function jRem() {
$('#list li').has('input:checked').remove();
}

[#72684] Wednesday, February 5, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
angelr

Total Points: 399
Total Questions: 96
Total Answers: 101

Location: Finland
Member since Sun, May 21, 2023
1 Year ago
;