0

I need to get the values of all checkboxes that are currently checked using jquery, I suppose I would put it all in an array, but I am having trouble doing that. Would anyone be able to point me in the write direction.

This is what I am using so far. I am trying to send all of the values that are currently checked to a div I have.

function cityPopulate() {


        var arr44 = new Array();   
        var cityNames22 = $("input[name=city_select[]]:checked").each(function(){arr44.push(this.value);});



        $("#city_pop").append(cityNames22.val());
    }

        When I try the code above, it just gives me the value of the first checkbox I check only. Not all of the rest. 
Bill paxton
  • 95
  • 2
  • 3
  • 9

2 Answers2

3

Without seeing the code you have I'm guessing at your exact schema, but using map() on your checkboxes with the class you specify to create an array should work, try this:

var checkboxValues = $('.myCheckbox:checked').map(function() {
    return $(this).val();
}).get();

checkboxValues would then contain an array with all the values of the checked checkboxes.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • This actually working cause I see in the javascript error it giving me all of the values now, but how would I display this array. Now it just won't display, it give me the error "object has no method val" – Bill paxton Mar 13 '12 at 21:22
  • To display an array as a string you need to `join()` it - `$("#city_pop").append(checkboxValues.join(','));` – Rory McCrossan Mar 14 '12 at 08:49
1

Depending on the class you have assigned to your checkboxes, it will look something like this:

var values = [];

$('.checkboxclass').each(function(){
  var $this = $(this);
  if ($this.is(':checked')) {
    values.push($this.val());
  }
});
rjz
  • 16,182
  • 3
  • 36
  • 35