NichoDiaz NichoDiaz - 4 years ago 90
Javascript Question

Removing Values From An Array When CheckMarked

I want to remove the values of an array when they are check marked.

My HTML

<ul id="keyWords">
<li><input id="check" name="check" type="checkbox">thirteen</li>
<li><input id="check" name="check" type="checkbox">twelve</li>
<li><input id="check" name="check" type="checkbox">eleven</li>
<li><input id="check" name="check" type="checkbox">ten</li>
<li><input id="check" name="check" type="checkbox">nine</li>
<li><input id="check" name="check" type="checkbox">eight</li>
<li><input id="check" name="check" type="checkbox">one</li>
</ul>


When this button is clicked i need the check marked values to be removed from the array

<button id="clearChecked">Clear Checked Items</button>


And this is the jquery function I am trying to use but it is not working.
i need the function to remove the checked boxed values from the array named
localArray
and the keywords are in the
ul
of
keyWords


$('#clearChecked').click(function() {
var keyWords = $('#keyWords').html();
if ((index = keyWords.indexOf($(localArray.this).val())) !== -1) {
localArray.splice(index, 1);
} else {
if ($(keyWords.this).is(':checked')) {
localArray.push($(this).val());
}
}
});

Answer Source

Don't bother with splicing the array, just create a new one:

var newArray = [];
$('#clearChecked').click(function() {
  $('#keyWords > input').each( function (n, obj) {
      if ($(obj).is(':checked')) {
          newArray.push($(obj).val());
      }
  }
});
localArray = newArray;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download