Ryan
Ryan

Reputation: 29

Log all items of checked checkboxes to console

I have three checkboxes which have a class name of (names). I am trying to say if the checkbox is checked log the value to the console.

if( $('.names').is(':checked') ){
        console.log($('.names').val()); 
    }else{
        console.log('null'); 
    }

However, this is only logging the first value to the console (when there is more than one ticked).

Do i need to create an array and log that?

Upvotes: 2

Views: 4136

Answers (3)

David Thomas
David Thomas

Reputation: 253318

While you have a correct answer posted already, it's worth noting that jQuery is not required for this to be 'easy'; it's quite possible in vanilla JavaScript:

// creating a named function to handle the change-event (later):
function logToConsole() {
  // retrieves a collection of elements that match the CSS selector:
  var checked = document.querySelectorAll('input[type=checkbox].names:checked'),
    // converts the collection to an Array:
    values = Array.prototype.slice.call(checked, 0)

    // map iterates over the Array returned by
    // Array.prototype.slice():
    .map(function(checkbox) {
    // checkbox is the Array Element itself:

      // returning the value of the checked checkbox:
      return checkbox.value;
    });

  // if the collection has a length other than 0:
  if (checked.length) {

    // outputs the array of values to the console:
    console.log(values);
  }
}

document.querySelector('form').addEventListener('change', logToConsole);
<form action="#" method="post">
  <fieldset>
    <legend>Check any of the check-boxes to see the values of those check-boxes logged to the console</legend>
    <label>value: 3
      <input value="3" class="names" type="checkbox" />
    </label>
    <label>value: 4
      <input value="4" class="names" type="checkbox" />
    </label>
    <label>value: 5
      <input value="5" class="names" type="checkbox" />
    </label>
    <label>value: 6
      <input value="6" class="names" type="checkbox" />
    </label>
  </fieldset>
</form>

Upvotes: 1

Werner
Werner

Reputation: 2154

Vanilla Javascript solution:

[].forEach.call(document.querySelectorAll('.names:checked'), function (cb) {
    console.log(cb.value);
});

And if you wan't that for older browsers as well:

var cbs = document.querySelectorAll('.names:checked');
for(var i = 0; i < cbs.length; i++)
    console.log(cbs[i].value);

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

The getter version of val() will return the value of the first element only.

One solution is to get an array of all the checked values and print it

var checked = $('.names:checked').map(function() {
  return this.value;
}).get();
if (checked.length) {
  console.log(checked);
} else {
  console.log('null');
}

Upvotes: 2

Related Questions