同时过帐选中和未选中的复选框


Posting both checked and unchecked checkboxes

我正在尝试在web表单中制作一系列复选框,根据是否选中它们,这些复选框将在下一个php页面上显示"true"或"false"。我决定,对于每个复选框(value="true"),我都会有一个隐藏的复选框(value="false"),它总是相反的(当复选框被选中时,隐藏复选框被取消选中等)。我正在使用jQuery来做这件事。

"td"元素的数量未知(可以使用按钮无限次克隆"td",以提交多个值)。出于测试目的,我将警报添加到jQuery中。

当我将jQuery代码和隐藏复选框添加到我的源代码中时(为了测试目的,我使其可见),代码无法工作,我的网页上的所有其他jQuery都停止了工作!

jQuery代码:

$(document).ready(function(){
    /***post all 'required' checkboxes instead of just checked ones***/
    $(".required").click(function(event){
        event.preventDefault();
        alert("test");
        nextIndex = this.index() + 1;
        alert(nextIndex);
        $(".required:eq(nextIndex)").attr("checked", !.required:eq(nextIndex).attr("checked"));
    });
});

HTML:

<td>
    <input type="checkbox" class="required" name="required[]" value="true">
    <input type="checkbox" class="required" name="required[]" value="false" style="display: none;" checked>
</td>

您不必隐藏其中一个复选框。这里有一个解决方案,应该可以实现你想要的:

<input type="hidden" name="required" value="false" />
<input type="checkbox" name="required" value="true" />

如果未选中该复选框,则将使用false值提交隐藏字段。如果选中复选框,则复选框中的true值将覆盖隐藏输入中的false值。

只要您可以将每个复选框命名为稍微不同的名称,它就会起作用。

以下内容也适用于值数组:

<input type="hidden" name="required[0]" value="false" />
<input type="checkbox" name="required[0]" value="true" />
<input type="hidden" name="required[n]" value="false" />
<input type="checkbox" name="required[n]" value="true" />

这样,您就不需要任何客户端javascript来切换隐藏的复选框。

这一行可能会导致中断:

$(".required:eq(nextIndex)").attr("checked", !.required:eq(nextIndex).attr("checked"));

你的意思可能是:

$(".required:eq(" + nextIndex + ")").attr("checked", !$('.required:eq(' + nextIndex + ')').attr("checked"));

还要注意,您需要将nextIndex从引号中去掉。

我的猜测是,您的javascript控制台会抛出与此相关的某种错误。

编辑:

我注意到的另一个错误是:

nextIndex = this.index() + 1;

.index()是一个jquery函数,它必须在jquery对象上调用。this是被点击的元素,所以你需要说:

nextIndex = $(this).index() + 1;

顺便说一句,你可能想看看jQuery的.next()函数。它会让你免于nextIndex的胡言乱语。

如果你这样命名你的复选框,你不一定有一个索引可以使用:

<input type="checkbox" name="checkbox_name[]" />

那么,假设您可以依赖javascript,那么jQuery的这个片段应该对您有用。

$('form').submit(function(){
    $(":checkbox:not(:checked)").each(function(element, index){
        $(this).attr({value: 'false', checked:'checked'});
    });
    return true;
});

这将遍历所有未选中的复选框,选中它们,并将它们的值设置为false。以下是您在PHP中获得的内容:

[checkbox_name] => Array
    (
        [0] => off
        [1] => on
        [2] => off
    )

代替:

[checkbox_name] => Array
    (
        [0] => on
    )