Panama Jack
Panama Jack

Reputation: 24448

Get checkboxes on the page with jQuery and put the values into string to send ajax call

What I'm trying to do is use jQuery to grab any checkboxes that are checked on the page. The boxes are dynamically created using a specific ID number of each one for the ID and Value.

What is the easiest way about getting it to grab the values of each checked item? Then check if less than or greater than 3 is checked. If only 3 are checked then send the values of each checkbox to my php script. I'm using a regular button on the page so I will proably have to use the .click method since its not actually part of a form to submit. I've seen several examples around here but not quite what I'm trying to do.

$('#mybtn').live('click',function(){         
       $("input[type=checkbox]").each(function() {
       // I guess do something here.
)};
)};

Upvotes: 0

Views: 767

Answers (4)

jsweazy
jsweazy

Reputation: 1621

the code i believe you are wanting is this

$('#mybtn').live('click',function(){  
    var num_checked = $("input[type=checkbox]:checked").length;
    var checkbox_values = new Array();
    if( num_checked > 3 ) {
        //its greater than 3
        //do what you need to do
    } else if( num_checked < 3 ) {
        //its less than 3
        //do what you need to do
    }else {
        //it equals 3
        //do what you need to do

        //go thru and add values to array
        $("input[type=checkbox]:checked").each(function() {
            checkbox_values.push($(this).val());
        });
    }
});

if you want to send email of variables you can output array checkbox_values to php

Upvotes: 2

James Chen
James Chen

Reputation: 10874

It's simple to grab all checked checkboxes:

var checked = $('input[type=checkbox]:checked'),
  count = checked.length;

if (count == 3) {
  values = $.map(checked, function(i){
    return $(this).val();
  });
}

Then do whatever you want on the values array.

Upvotes: 0

Loktar
Loktar

Reputation: 35309

You can get how many are checked using

$("input[type=checkbox]:checked").length

http://jsfiddle.net/XKRRL/7/

Not really sure what you want to do with the ones that are checked, but the js fiddle loops through the checked ones. From there you could grab id's etc.

full code

$(function() {
    $('#mybtn').live('click', function() {
        var checkedBoxes = $("input[type=checkbox]:checked"),
            checkedNum = checkedBoxes.length;

        if(checkedNum  === 3){
            for(var i=0; i< checkedNum; i++){
               alert($(checkedBoxes).eq(i).val());
            } 
        }

    });
});

Upvotes: 0

Mark Rose
Mark Rose

Reputation: 981

If all your checkboxes are in a form, you can do $('#form_id').serialize();

Upvotes: 1

Related Questions