douxidang9092 2017-02-28 19:25
浏览 36
已采纳

数组仅存储值为1(不为0)的复选框[重复]

I have checkboxes which change value using JavaScript and I want to store values of all checkboxes in a PHP array. But if the user changes the value of one checkbox to "0", the array created has only 2 values (1,1) instead of (1,0,1).

HTML

<input type="checkbox" name="cbox1[]" checked="checked" value="1" class="chbo">
<input type="checkbox" name="cbox1[]" checked="checked" value="1" class="chbo">
<input type="checkbox" name="cbox1[]" checked="checked" value="1" class="chbo">

PHP

$wer=$_POST['cbox1'];
echo implode(",",$wer);

Jquery

$(document).on('click', '.chbo', function() {
this.value ^= 1;
console.log(this.value);
});
</div>
  • 写回答

2条回答 默认 最新

  • douxi3554 2017-02-28 19:28
    关注

    Only successful (checked) controls are submitted. You need to add a hidden input with the default value before the checkbox. Notice you need to hard code the indexes so that the hidden default matches the checkbox value:

    <input type="hidden"   name="cbox1[0]" value="0" class="chbo">
    <input type="checkbox" name="cbox1[0]" value="1" class="chbo" checked="checked">
    <input type="hidden"   name="cbox1[1]" value="0" class="chbo">
    <input type="checkbox" name="cbox1[1]" value="1" class="chbo" checked="checked">
    

    So if not checked, only the hidden cbox1[0] with value 0 will be submitted. If checked, then cbox1[0] with value 1 will overwrite the hidden input.

    You won't need the JavaScript now because you can change the checkbox to value 0 but if it is not checked it won't be submitted.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题