Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

php - Post array of multiple checkbox values

Why is only one value of the "db" checkbox values array being sent to the server side script?

JQUERY:

$(".db").live("change", function() {
    $(this).add($(this).next("label")).add($(this).next().next("br")).remove().insertAfter(".db:last + label + br"); 
    var url = "myurl.php";
    var db = [];
    $.each($('.db:checked'), function() {
        db.push($(this).val()); 
    });
    if(db.length == 0) { 
        db = "none"; 
    }       
    $.post(url, {db: db}, function(response) {
        $("#dbdisplay").html(response); 
    });
    return true;
});

HTML:

<input type="checkbox" name="db[]" class="db" value="track"/><label for="track">track</label></br>
<input type="checkbox" name="db[]" class="db" value="gps"/><label for="gps">gps</label></br>
<input type="checkbox" name="db[]" class="db" value="accounting"/><label for="accounting">accounting</label></br>

Edit: I ended up answering my own question, but does anyone have documentation (or an explanation) of why this is necessary? It was difficult for me to find the exact answer (thus the posthumous post).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I agree with @jjclarkson. Just to add, instead of pushing your ids to an array, you can use $.map:

$(".db").live("change", function() {
    $(this).add($(this).next("label")).add($(this).next().next("br")).remove().insertAfter(".db:last + label + br"); 
    var url = "myurl.php";

    var db = $('.db:checked').map(function(i,n) {
        return $(n).val();
    }).get(); //get converts it to an array

    if(db.length == 0) { 
        db = "none"; 
    }       
    $.post(url, {'db[]': db}, function(response) {
        $("#dbdisplay").html(response); 
    });
    return true;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...