当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to take the checkbox value as Array

问题描述:

I have three checkbox. I want to get the checked values.I'm using jquery but i dont get it properly

html

<label class='checkbox'><input type='checkbox' name='' class='group1' value=""/>Period 1</label>

<label class='checkbox'><input type='checkbox' name='' class='group1' value="" class='termcls' />period 2</label>

<label class='checkbox'><input type='checkbox' name='' class='group1' value=""/>All</label>

jquery

var values = $('input:checkbox:checked.group1').map(function () {

return this.value;

}).get();

alert(values[0]);

Please help me

网友答案:

simply try

var values =[];
$('input.group1:checkbox:checked').each(function () {
    value.push( this.value );
});

console.log( values );

Since Arun hasn't posted an answer, so shameless copying it from his fiddle here :)

$('input:checkbox.group1').change(function() {
  var values = $('input:checkbox:checked.group1').map(function() {
    return this.value;
  }).get();

  alert(values);
})
网友答案:

Put values for each checkbox and use like this

function getoutput() {
  var values = [];
  $('.group1:checked').each(function() {
    values.push($(this).val());
  });
  console.log(values);
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<label class='checkbox'>
  <input type='checkbox' name='' class='group1' value="1" />Period 1</label>
<label class='checkbox'>
  <input type='checkbox' name='' class='group1' value="2" class='termcls' />period 2</label>
<label class='checkbox'>
  <input type='checkbox' name='' class='group1' value="3" />All</label>

<input type="button" value="Get Selected" onclick="getoutput()">
网友答案:

I would use a for each to look over the values then use ".is(':checked')" to check which ones are checked.

网友答案:

You can try this

note: value is blank in your html right now, there must be a value to get it into the .map() function

var values = $('input.group1:checkbox:checked').map(function () {
   return this.value;
}).get().join(',');

Demo

分享给朋友:
您可能感兴趣的文章:
随机阅读: