【发布时间】:2014-11-17 03:42:42
【问题描述】:
我无法获取选中和未选中复选框的值。当复选框被选中时,它将获取该特定复选框的值,而当复选框未选中时,未选中复选框的值将为 0。
这是我的html代码:
<table border="0" cellspacing="0" cellpadding="1">
<tbody>
<tr style="height: 40px;">
<td style="width: 240px;"><input type="checkbox" name="checkbox[]" value="5"> Barangay business permit </td>
<td style="width: 240px;"><input type="checkbox" name="checkbox[]" value="10"> Business plate </td>
<td style="width: 240px;"><input type="checkbox" name="checkbox[]" value="20"> Sanitary inspection fee </td>
</tr>
<tr style="height: 40px;">
<td style="width: 240px;"><input type="checkbox" name="checkbox[]" value="30"> Environmental clearance </td>
<td style="width: 240px;"><input type="checkbox" name="checkbox[]" value="40"> Barangay development </td>
<td style="width: 240px;"><input type="checkbox" name="checkbox[]" value="50"> building permit </td>
</tr>
<tr style="height: 40px;">
<td style="width: 240px;"><input type="checkbox" name="checkbox[]" value="60"> Electrical inspection </td>
<td style="width: 240px;"><input type="checkbox" name="checkbox[]" value="70"> Mechanical inspection </td>
<td style="width: 240px;"><input type="checkbox" name="checkbox[]" value="80"> Plumbing inspection </td>
</tr>
</tbody>
</table>
<div class="" style="margin: auto; padding-top:20px;">Total <input type="text" name="total" style="color: #222222;" readonly/>
<input type="submit" name="register" value="Register" style="width: 100px; height:50px; margin:auto; color:#222222;">
</form>
PHP 代码:
$checkbox=$_POST['checkbox'];
for($i=0; $i<count($checkbox); $i++)
{
$num[$i]=$checkbox[$i];
}
Javascript 代码(用于获取每个复选框的值的功能,同时在总计字段中检查并生成总计。)
<script type="text/javascript">
$(function(){
var applications = [];
//bind the change event to the checkboxes
$('input[name="checkbox[]"]').change(function(){
var total = 0;
//get value from each selected ckeck box
$('input[name="checkbox[]"]:checked').each(function(){
var tval = $(this).val();
total += parseFloat(tval);
});
//finally display the total with a ₱ sign
$('input[name="total"]').val("₱ " + total);
// handle applications
var application = $.trim($(this)[0].nextSibling.nodeValue); // get the name
var i = applications.indexOf(application);
if(i != -1) {
applications.splice(i, 1); // remove if unchecked
} else {
applications.push(application); // push if checked
}
var temp = applications.join(', ');
$('input[name="applications"]').val(temp);
});
});
</script>
在实际测试中,我勾选了[0, 1, 0, 0, 1, 1, 0, 0, 0]表中的一些复选框。注:1表示勾选,0表示未勾选,以便清楚。
当我点击提交按钮并显示值时,我得到了这个
[0] => 10
[1] => 40
[2] => 50
但我想得到这样的值
[0] => 0
[1] => 10
[2] => 0
[3] => 0
[4] => 40
[5] => 50
[6] => 0
[7] => 0
[8] => 0
如何获得这些值?我需要将未选中的每个值都设为 0 和选中的值,然后将每个数组(按顺序)保存到数据库中。我真的需要帮助,我从网上搜索了它,但我没有找到解决我问题的正确方法。我认为我的 php 代码是错误的。
数据库名称:应用程序
表格:费用
列:ID、fee1、fee2、fee3、fee4、fee5、fee6、fee7、fee8、fee9
【问题讨论】:
-
未选中的不张贴
标签: php jquery html arrays checkbox