最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to push checked checkboxes values into an array? - Stack Overflow

programmeradmin2浏览0评论

I'd like to push checked checkboxes values into an array, but I'm having some issue because each time I try to add it into the array it stays empty, I am probably doing something wrong but can't figure out what.

/

HTML :

<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

Jquery :

$(document).ready(function () {

  var tmp = [];

  $("input").each(function() {
    if ($(this).is(':checked')) {
      var checked = ($(this).val());
      tmp.push(checked);
    }
  });

  $('#button').on('click', function () {
        alert(tmp);
  });

});

What am I doing wrong ?

I'd like to push checked checkboxes values into an array, but I'm having some issue because each time I try to add it into the array it stays empty, I am probably doing something wrong but can't figure out what.

http://jsfiddle/fx7su2rp/689/

HTML :

<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

Jquery :

$(document).ready(function () {

  var tmp = [];

  $("input").each(function() {
    if ($(this).is(':checked')) {
      var checked = ($(this).val());
      tmp.push(checked);
    }
  });

  $('#button').on('click', function () {
        alert(tmp);
  });

});

What am I doing wrong ?

Share Improve this question asked May 14, 2017 at 9:18 Horai NuriHorai Nuri 5,57817 gold badges84 silver badges136 bronze badges 2
  • Are you deliberately not allowing values to be removed from the array, or is that your next step? – David Thomas Commented May 14, 2017 at 9:22
  • @DavidThomas If the user removes a value I'll update it onto the array when submiting – Horai Nuri Commented May 14, 2017 at 9:25
Add a ment  | 

7 Answers 7

Reset to default 5

You are not invoking checkbox change event. Use this:

$("input[name='checkbox']").change(function() {
  var checked = $(this).val();
  if ($(this).is(':checked')) {
    tmp.push(checked);
  } else {
    tmp.splice($.inArray(checked, tmp),1);
  }
});

http://jsfiddle/fx7su2rp/694/

You are verifying if they are checked at the beginning (when none is checked) so this is why you get that empty array.

You should be handling clicks on the inputs in order to update the array. Check this out.

$(document).ready(function () {

  var tmp = [];

  $("input").click(function() {
    if ($(this).is(':checked')) {
      var checked = ($(this).val());
      tmp.push(checked);
    } else {
      tmp.splice($.inArray(checked, tmp),1);
    }
  });

  $('#button').on('click', function () {
        alert(tmp);
  });

});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

Notice the $('input').click() there.

You need to handle checked event of each checkbox.

So that you can push it into array For more detail, you can see here

$(document).ready(function () {

  var tmp = [];
  
  $("input").each(function() {
    $(this).change(function() {
    if(this.checked) {
      tmp.push(this.checked);
    }
});})
 
  $('#button').on('click', function () {
		alert(tmp);
    console.log(tmp);
  });
  
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

Either you can do on change as the other sais, but it's more effective to only run the code when the user presses the button, so make a function and call that function when the user presses the button:

http://jsfiddle/fx7su2rp/693/

$(document).ready(function () {


  $('#button').on('click', function () {
        alert(check_boxes());
  });

});

function check_boxes() {
var tmp = [];
  $("input").each(function() {
    if ($(this).is(':checked')) {
      var checked = ($(this).val());
      tmp.push(checked);
    }
  });
  return tmp;
}

Add a click function on your checkbox and each click, if checked, then push the value in tmp variable.

  $('#button').on('click', function () {
  var tmp = [];
      $("input").each(function() {
          if ($(this).is(':checked')) {
          var checked = ($(this).val());
          tmp.push(checked);
        }
      });
  alert(tmp);
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

As other answers already suggested, you have to update your values array anytime a change event occurs on any checkbox you wish to monitor.

Other answers work just fine, but I thought I'd post a more plain javascript answer. I think this is a bit cleaner and more expressive than a jQuery .each() loop, and saves us from querying values in, pushing into, and splicing from an intermediate array manually.

Let's create a regular array containing your checkboxes called checkboxesArray in addition to the jQuery collection, and filter then map that array in our change handler:

$(document).ready(function () {

  let $checkboxes = $('[name="checkbox"]');
  let checkboxesArray = [].slice.call($checkboxes);
  let $output = $('#output');
  let values = [];
  
  $checkboxes.on('change', () => {
    values = checkboxesArray
      .filter((checkbox) => checkbox.checked)
      .map((checkbox) => checkbox.value);
      
    // Preview:
    $output.append('<div>' + values.join(', ') + '</div>');
  });
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="checkbox" value="1" type="checkbox" />
<input name="checkbox" value="2" type="checkbox" />
<input name="checkbox" value="3" type="checkbox" />
<input name="checkbox" value="4" type="checkbox" />
<button id="button" type="button">button</button>

<div id="output"></div>

This will help you :

$("#button").click(function (e) { 
     var tmp = [];              
     $('.tmp').each(function(){
     if ($(this).is(':checked')) {
     var checked = ($(this).val());
     tmp.push(checked);
   }
 });
 console.log(tmp);
}
发布评论

评论列表(0)

  1. 暂无评论