我在表单中添加了一个复选框,用户可以向其中动态添加行。可以看到表格 here .
我使用数组将每一行的值传递给 PHP 电子邮件生成器,并且对于其他输入都可以正常工作,但我无法使复选框起作用。复选框输入当前看起来像这样:
<input type="checkbox" name="mailing[]" value="Yes">
然后在 PHP 中我有这个:
$mailing = trim(stripslashes($_POST['mailing'][$i]));
但它没有按预期工作,即我只看到选中的第一个复选框为"is",而选中的后续复选框则没有。
另一个问题是我希望为未选中的复选框生成值“否”。
有人可以帮忙吗?
谢谢,
尼克
表格:
<form method="post" action="bookingenginetest.php">
<p>
<input type="checkbox" name="mailing[]" value="Yes">
<label>Full Name:</label> <input type="text" name="name[]">
<label>Email:</label> <input type="text" name="email[]">
<label>Telephone:</label> <input type="text" name="telephone[]">
<span class="remove">Remove</span>
</p>
<p>
<span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" />
</p>
</form>
克隆脚本:
$(document).ready(function() {
$(".add").click(function() {
var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
x.find('input').each(function() { this.value = ''; });
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
});
最佳答案
$mailing = array();
foreach($_POST as $v){
$mailing[] = trim(stripslashes($v));
}
要处理未选中的复选框,最好为每个复选框设置一个唯一的值:
<input type="checkbox" name="mailing[1]" value="Yes">
<input type="checkbox" name="mailing[2]" value="Yes">
或
<input type="checkbox" name="mailing[a]" value="Yes">
<input type="checkbox" name="mailing[b]" value="Yes">
然后有一个复选框列表:
$boxes = array(1,2,3);
$mailing = array();
$p = array_key_exists('mailing',$_POST) ? $_POST['mailing'] : array();
foreach($boxes as $v){
if(array_key_exists($v,$p)){
$mailing[$v] = trim(stripslashes($p[$v]));
}else{
$mailing[$v] = 'No';
}
}
print_r($mailing);
您也可以将其与多个复选框一起使用:
$boxes = 3;
$mailing = array();
$p = array_key_exists('mailing',$_POST) ? $_POST['mailing'] : array();
for($v = 0; $v < $boxes; $v++){
if(array_key_exists($v,$p)){
$mailing[$v] = trim(stripslashes($p[$v]));
}else{
$mailing[$v] = 'No';
}
}
print_r($mailing);
关于php - 如何将一组选中/未选中的复选框值传递给 PHP 电子邮件生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6376112/