user11424912
user11424912

Reputation:

Getting multiple values from checked checkboxes Javascript

I'm wondering if there would be away to get the values of checked checkboxes and than use the values in the filter function in my DeleteObject function.

<div style="text-align:center" class="list">
  <small>Walls:</small><input id="deleteCheckbox" type="checkbox" value="Wall">
  <small>Doors:</small><input id="deleteCheckbox" type="checkbox" value="Door">
  <small>Traps:</small><input id="deleteCheckbox" type="checkbox" value="SlowTrap"><br>
  <small>Mines:</small><input id="deleteCheckbox" type="checkbox" value="GoldMine">
</div>

Javascript:

function DeleteObject() {
  var b = Game.currentGame.ui.buildings;
  Object.keys(b).filter(function(e) {

    return CheckBoxValuesHere == b[e].type;

  }).forEach(function(i) {
    Game.currentGame.network.sendRpc({
      name: "DeleteObject",
      uid: b[i].uid
    })
  })
}

Upvotes: 0

Views: 97

Answers (3)

Martin Spd
Martin Spd

Reputation: 53

Add unique names or IDs to each checkbox and assign them listeners to click event (in JS code) or directly in HTML. Then in JS refer to checkbox value with document.getElementById(<ID>).value.

Upvotes: 0

some
some

Reputation: 49632

function getItemsToDelete() {
  // get a nodeList of all selected elements,
  // convert it to an array and return an
  // array of the values.
  return Array.from(
    document.querySelectorAll(
      'input[name=deleteCheckbox]:checked'
    )
  ).map( item => item.value );
}
console.log(getItemsToDelete());
<ul style="list-style:none">
  <li><input name="deleteCheckbox" type="checkbox" value="Wall"><small>Walls</small></li>
  <li><input name="deleteCheckbox" type="checkbox" value="Door" checked><small>Doors</small></li>
  <li><input name="deleteCheckbox" type="checkbox" value="SlowTrap"><small>Traps</small></li>
  <li><input name="deleteCheckbox" type="checkbox" value="GoldMine"><small>Mines</small></li>
</ul>

Upvotes: 0

random
random

Reputation: 7899

As mentioned in the comments, id's should be unique. To get the values of checked checkboxes, add change event to the input with type checkbox and then grab input with checked checkboxes.

document.querySelectorAll('input[type="checkbox"]')
    .forEach(input => {
        input.addEventListener('change', function() {
            const values = [...document.querySelectorAll('input:checked')].map(input => input.value);
            console.log(values);
        });
    });
<div style="text-align:center" class="list">
    <small>Walls:</small><input id="deleteCheckbox" type="checkbox" value="Wall">
    <small>Doors:</small><input id="deleteCheckbox" type="checkbox" value="Door">
    <small>Traps:</small><input id="deleteCheckbox" type="checkbox" value="SlowTrap"><br>
    <small>Mines:</small><input id="deleteCheckbox" type="checkbox" value="GoldMine">
</div>

Upvotes: 1

Related Questions