开发者

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 check开发者_运维技巧box 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.
)};
)};


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


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


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());
            } 
        }

    });
});


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜