How to send a checkbox group via ajax in jquery?

前端 未结 4 833
暗喜
暗喜 2021-01-14 07:39

I need to send a group of checkboxes (with some other data as well) via ajax in jquery.

What I\'ve done so far is:

var arr = $(\'#somediv input[type         


        
相关标签:
4条回答
  • 2021-01-14 08:28

    Use serialize(), as val() just takes the value of the first element in the jquery collection. http://api.jquery.com/serialize/

    var postdata = $('#somediv input[type="checkbox"]').serialize();
    $.post("/somephpfile.php", postdata, function(data) {...
    
    0 讨论(0)
  • 2021-01-14 08:40

    Ran into a similar problem and after much pulling of hair fixed it with SerializeArray

    HTML

    <input type="checkbox" name="userList[]" value="<?=$userID;?>" /><?= $userName;?>
    

    jQuery

    var userList = $('input[type=checkbox]:checked').serializeArray();
    

    PHP

    $userList = $_POST['userList'];
    for($i=0;$i<sizeof($userList);$i++)
    {
        $userID = $userList[$i][value] ;
        //Insert $userID to DB
    }
    
    0 讨论(0)
  • 2021-01-14 08:42

    You may be looking for .serialize

    A more generic solution would be to have a form with all the parameters and then serialize it.

    0 讨论(0)
  • 2021-01-14 08:45

    Try the following:

            var selectedItems = [];
            $('#somediv input[type="checkbox"]:checked').each(function () {
                    selectedItems .push($(this).val());
            });
    
            var postData = { "str": str, "arr": selectedItems };
            $.ajax({
                type: "POST",
                url: "/somephpfile.php",
                data: postData,
                traditional: true,
                success: function (data) {
                    ...
                }
            });
    

    PS I'm assuming you know about serialize and it's not right for your scenario. Definitely check that out first (although it will serialize the whole element). This means if your checkboxes don't have the same NAME attribute or you need to control the variable name they are passed in as you can use my suggestion to do it manually.

    0 讨论(0)
提交回复
热议问题