因此,我有一组复选框,这些复选框是用以下代码动态创建的:
<?php foreach($candies as $candy): ?>
<a style="cursor:pointer;" class="candy list-group-item" data-id="<?php echo $candy['candy_id']; ?>" data-toggle="popover" data-placement="top" data-html="true" data-trigger="hover" data-content="<img src='<?php echo $candy['candy_img']; ?>'>"><?php echo $candy['candy_name']; ?></a>
<input type="checkbox" id="<?php echo $candy['candy_id']; ?>" name="<?php echo $candy['candy_name']; ?>" style="display:none;" />
<?php endforeach; ?>
这导致了以下(缩短)代码:
<ul class="list-group">
<a style="cursor:pointer;" class="candy list-group-item" data-id="1" data-toggle="popover" data-placement="top" data-html="true" data-trigger="hover" data-content="<img src='http://www.groovycandies.com/pc/catalog/8992_General.jpg'>" data-original-title="" title="">Raspberry Gummi Bears</a>
<input type="checkbox" id="1" name="Raspberry Gummi Bears" style="display:none;">
<a style="cursor:pointer;" class="candy list-group-item" data-id="2" data-toggle="popover" data-placement="top" data-html="true" data-trigger="hover" data-content="<img src='http://www.groovycandies.com/pc/catalog/candy-runts-5.jpg'>" data-original-title="" title="">Runts</a>
<input type="checkbox" id="2" name="Runts" style="display:none;">
...
</ul>
然后我有javascript,当单击上面的<a>
时,正确的checkbox
被选中或未选中。
<script type="text/javascript">
$(".candy").click(function(){
var id = $(this).data('id');
var checkbox = $("#"+id).prop("checked");
if ( checkbox != true) {
$("#"+id).prop("checked", true);
$(this).attr("class","candy list-group-item active");
}
else
{
$("#"+id).prop("checked", false);
$(this).attr("class","candy list-group-item");
}
});
</script>
现在我要提交表格了..。但在我这么做之前,我还想做一件事。我搞不懂。
我想在php中创建一个数组,我的理解是:<?php $candies = array(); ?>
,这将创建一个空白数组。现在,当选中复选框时,我希望将复选框的名称添加到数组中。或者当未选中复选框时,它将从数组中移除。我希望在提交表格之前做到这一点。我怎样才能做到这一点?
发布于 2014-01-18 17:34:44
这可以在没有链接的情况下完成,而javascript只需使用以下标签即可完成:
通过注意输入的name
属性,使复选框成为数组。附加的[]
向服务器发送一个数组。
<p><label><input type="checkbox" name="candies[]" value="Raspberry Gummi Bears" /> Raspberry Gummi Bears</label></p>
<p><label><input type="checkbox" name="candies[]" value="Runts" /> Runts</label></p>
然后在PHP端:
<?php
$candies = $_POST["candies"];
print_r($candies);
https://stackoverflow.com/questions/21212115
复制相似问题