Nic*_*ick 3 php forms arrays checkbox
我在用户可以动态添加行的表单中添加了一个复选框。您可以在此处查看表格。
我使用一个数组将每一行的值传递给 PHP 电子邮件生成器,并且对于其他输入都可以正常工作,但是我无法让复选框工作。复选框输入目前看起来像这样:
<input type="checkbox" name="mailing[]" value="Yes">
Run Code Online (Sandbox Code Playgroud)
然后在PHP中我有这个:
$mailing = trim(stripslashes($_POST['mailing'][$i]));
Run Code Online (Sandbox Code Playgroud)
但它没有按预期工作,即我只看到第一个选中的复选框为“是”,而随后选中的复选框没有任何内容。
另一个问题是,我希望为未选中的复选框生成值“否”。
有人可以帮忙吗?
谢谢,
缺口
形式:
<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>
Run Code Online (Sandbox Code Playgroud)
克隆脚本:
$(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();
});
});
Run Code Online (Sandbox Code Playgroud)
$mailing = array();
foreach($_POST as $v){
$mailing[] = trim(stripslashes($v));
}
Run Code Online (Sandbox Code Playgroud)
要处理未选中的框,最好为每个复选框设置一个唯一值:
<input type="checkbox" name="mailing[1]" value="Yes">
<input type="checkbox" name="mailing[2]" value="Yes">
Run Code Online (Sandbox Code Playgroud)
或者
<input type="checkbox" name="mailing[a]" value="Yes">
<input type="checkbox" name="mailing[b]" value="Yes">
Run Code Online (Sandbox Code Playgroud)
然后有一个复选框列表:
$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);
Run Code Online (Sandbox Code Playgroud)
您也可以将其与多个复选框一起使用:
$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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21947 次 |
| 最近记录: |