Saphire_80 Saphire_80 - 4 months ago 7
HTML Question

Adding removing items from list

I have a simple question. Googled this a lot, but was not able to find a suitable solution. I have a list, based on 5 checkboxes.

abc.html

<li id="DisplaySelection"> </li>
{{form.Test1 }} //checkbox1
....
{{form.Test5 }} //checkbox5


main.js

document.getElementById('Test1').onclick = function() {
if ( this.checked ) {
var word = 'Selection1';
document.getElementById('DisplaySelection').innerHTML += ('<li>'+word+'</li>');
}
else {
// remove same word from list
}
}

document.getElementById('Test5').onclick = function() {
if ( this.checked ) {
word = 'Selection5';
document.getElementById('DisplaySelection').innerHTML += ('<li>'+word+'</li>');
}
else
// remove from list
}
}


I want to accomplish the remove part. That is, if the checkbox is unchecked remove that item from the list. How do I get this working? Yes, I'm new to JavaScript.

Thanks for the answers but the problem is I have Django form fields and not html and I don't know how to add value and class attributes to them.

Answer

I think you want some thing this ....

var classname = document.getElementsByClassName('item');

for (var i = 0; i < classname.length; i++) {
  classname[i].addEventListener('click', myFunction);
}

function myFunction() {
  if (this.checked) {
    document.getElementById('selectedItems').innerHTML += '<li id="' + this.value + '">' + this.value + '</li>';
  } else {
    var elem = document.getElementById(this.value);
    elem.parentNode.removeChild(elem);
  }
}
<h4>Selected Items</h4>
<ul id='selectedItems'>
</ul>
<div>
  <h4>Select Items</h4>
  <ul>
    <li>
      <input type='checkbox' value='item1' class='item'>Item1</li>
    <li>
      <input type='checkbox' value='item2' class='item'>Item2</li>
    <li>
      <input type='checkbox' value='item3' class='item'>Item3</li>
  </ul>
</div>

Comments