将所有已选中复选框的项目记录到控制台

时间:2015-10-21 10:53:37

标签: javascript jquery checkbox console.log

我有三个复选框,其名称为(名称)。我试图说,如果选中该复选框,请将值记录到控制台。

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

但是,这只是将第一个值记录到控制台(当勾选多个时)。

我是否需要创建一个数组并记录下来?

3 个答案:

答案 0 :(得分:2)

val()的getter版本将仅返回第一个元素的值。

一种解决方案是获取所有已检查值的数组并将其打印



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




答案 1 :(得分:0)

虽然您已经发布了正确的答案,但值得注意的是,jQuery并不是必需的,因为它很容易&#39 ;;它在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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

Vanilla Javascript解决方案:

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

如果您不喜欢旧浏览器:

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