2013-01-20 66 views
0

我在网上搜索和堆栈,但我找不到一种方法来解决我的问题 所以我希望有人可以帮助我 我有一个复选框相同的名称“shopitem [] “我想,以检查是否复选框被检查,然后把他们的值作为阵列,如‘1,3,5,7’的PHP代码与阿贾克斯回复多个复选框值由jquery

herere是我的代码:

<form id="ShopItemForm" class="ShopItemForm" method="post" name="ShopItemForm"> 
    <input class="ShopItem" checked="checked" name="ShopeItem[]" id="1" value="1" type="checkbox">1 
    <input class="ShopItem" name="ShopeItem[]" id="2" value="2" type="checkbox">2 
    <input class="ShopItem" checked="checked" name="ShopeItem[]" id="3" value="3" type="checkbox">3 
    <input class="ShopItem" name="ShopeItem[]" id="4" value="4" type="checkbox">4 
    <input class="ShopItem" name="ShopeItem[]" id="5" value="5" type="checkbox">5 

    <input name="submitShopItem" value="submit" class="button button-push" id="submitShopItem" type="submit"> 
</form> 

    $(function() { 
    $("#submitShopItem").click(function(e) { 
        e.preventDefault(); 
        // put all checked box to array checkedArray 
        var shopItem = 
        $("#shop-item-Loader").html(''); 
        $("#shop-item-Loader").html('load'); 
        $.ajax({ 
          type: "POST", 
          url: "checked.php", 
          data: "act=shopItem&ShopItem="+checkedArray, 
          cache: false, 
          success: function(html){ 
           alert(checkedArray); 
           $("#shop-item-Loader").html(''); 
           $("#shop-item-Loader").append(html); 
          } 
        }); 
       }); 
      }); 

我想要将所有新的检查值发送到像彗星分离字符串那样的ajax页面

+2

首先,使用你必须修复无效的html - 'name =“ShopeItem [] id =”1“=”“' – Andreas

+0

绝对!!!!!!!你有无效的HTML。 – Jai

+0

指针(对于HTML问题)未关闭的属性(特别是,它似乎是'name'和'id'),除非你指定了'html'的文档类型,否则'id'值是无效的(因为html < 5不允许'id'以数字开头)。 –

回答

1
var checkedArray = $("#ShopItemForm").find(":checked").map(function() { 
    return this.value; 
}).get(); 

console.log(checkedArray); 

Example

编辑
正如@DavidThomas最后森建议问题的唐斯: 为了得到一个逗号分隔的检查元件串你必须调用.join()checkedArray

checkedArray.join(); 

当喜欢这里

data: "act=shopItem&ShopItem="+checkedArray, 

是会自动完成

+0

它发送空字符串,如:,,, – OceanOne

+0

从[API文档为'map()'](http://api.jquery .com/map /),你应该使用'join()'。 –

+0

我使用了错误的值('id'而不是'value') - 对不起。用固定的html标记这应该工作 – Andreas

1

看到这个:http://jsfiddle.net/Q2Kdt/

$(function() { 
$("#submitShopItem").click(function (e) { 
    e.preventDefault(); 
    var result = ""; 
    $('input[type=checkbox]').each(function (e) { 
     if ($(this).is(':checked')) result = result + $(this).val() + ", "; 
    }); 
    alert(result); 
}); 
}); 

或名称本身检查:http://jsfiddle.net/Q2Kdt/2/

$(function() { 
$("#submitShopItem").click(function (e) { 
    e.preventDefault(); 
    var result = ""; 
    $("input[name*='ShopeItem[]']").filter(':checked').each(function (e) { 
     result = result + $(this).val() + ", "; 
    }); 
    alert(result); 
}); 
});