我有一堆默认选中的复选框。我的用户可能会取消选中一些复选框(如果有的话),并选中其余的复选框。

是否有任何方法使表单POST未选中的复选框,而不是选中的复选框?


当前回答

我知道这个问题已经提出3年了,但我找到了一个我认为非常有效的解决方案。

您可以检查$_POST变量是否已赋值,并将其保存在变量中。

$value = isset($_POST['checkboxname'] ? 'YES' : 'NO';

isset()函数检查$_POST变量是否被赋值。按照逻辑,如果它没有被分配,那么复选框就不会被选中。

其他回答

我更喜欢不需要javascript的解决方案(是的,我知道现在会有一些人把我归为勒德分子),但如果你像我一样,你想要能够显示复选框的默认/初始设置,然后让它保持或更新基于提交的表单,试试这个(建立在上面的几个想法上):

设置确定初始复选框状态的变量,然后使用服务器检查确定每次提交表单后的显示。

下面的例子创建了一个数组的数组(用于WordPress;同样适用于其他地方),然后使用服务器脚本确定复选框的状态,而不使用隐藏字段或javascript。

<?php

$options_array = array (
    array('list_companies_shortcode' , 'shortcode_list_companies' , 'List Companies Shortcode'),
    array('list_contacts_shortcode' , 'shortcode_list_contacts' , 'List Contacts Shortcode'),
    array('test_checkbox_1' , 'checked' , 'Label for Checkbox 1' , 'checkbox' , 'Some text to instruct the user on this checkbox use' ),
    array('test_checkbox_2' , '' , 'Label for Checkbox 2' , 'checkbox' , 'Some other text to instruct the user on this checkbox use' )
 ) ;


$name_value_array = array() ;
$name_label_array = array() ;
$field_type_array = array() ;
$field_descriptor_array = array() ;
foreach ( $options_array as $option_entry ) {
    $name_value_array[ $option_entry[0] ] = $option_entry[1] ;
    $name_label_array[ $option_entry[0] ] = $option_entry[2] ;
    if ( isset( $option_entry[3] ) ) {
        $field_type_array[ $option_entry[0] ] = $option_entry[3] ;
        $field_descriptor_array[ $option_entry[0] ] = $option_entry[4] ;
    } else {
        $field_type_array[ option_entry[0] ] = 'text' ;
        $field_descriptor_array[ $option_entry[0] ] = NULL ;
    } 
}

echo "<form action='' method='POST'>" ;
    foreach ( $name_value_array as $setting_name => $setting_value ) {
        if ( isset( $_POST[ 'submit' ] ) ) {
            if ( isset( $_POST[ $setting_name ] ) ) {
                $setting_value = $_POST[ $setting_name ] ;
            } else {
                $setting_value = '' ;
            }
        }   
        $setting_label = $option_name_label_array[ $setting_name ] ;
        $setting_field_type = $field_type_array[ $setting_name ] ;
        $setting_field_descriptor = $field_descriptor_array [ $setting_name ] ;
        echo "<label for=$setting_name >$setting_label</label>" ;
        switch ( $setting_field_type ) {
            case 'checkbox':
                echo "<input type='checkbox' id=" . $setting_name . " name=" . $setting_name . " value='checked' " . $setting_value . " >(" . $setting_field_descriptor . ")</input><br />" ;
                break ;
            default:
                echo "<input type='text' id=" . $setting_name . " name=" . $setting_name . " value=" . $setting_value . " ></input><br />" ;
        }
    }
    echo "<input type='submit' value='Submit' name='submit' >" ;
echo "</form>" ;

对于复选框,一个不使用隐藏类型值的简单方法是:

< >形式 <input type='checkbox' name='self - destruct' value='1'> > < /形式

在PHP中,对于表单数据的发布:

// Sanitize form POST data
$post = filter_var_array($_POST, FILTER_SANITIZE_STRING);

// set the default checkbox value
$selfDestruct = '0';
if(isset($post["selfdestruct"]))
    $selfDestruct = $post["selfdestruct"];

我个人最喜欢的是添加一个具有相同名称的隐藏字段,如果复选框未选中,将使用该字段。但解决方案并不像看起来那么容易。

如果你添加以下代码:

<form>
  <input type='hidden' value='0' name='selfdestruct'>
  <input type='checkbox' value='1' name='selfdestruct'>
</form>

浏览器不会真正关心您在这里做了什么。浏览器将把两个参数都发送给服务器,服务器必须决定如何处理它们。

例如,PHP将最后一个值作为要使用的值(参见:重复HTTP GET查询键的权威位置)

但是我使用过的其他系统(基于Java)是这样做的——它们只提供第一个值。 .NET会给你一个包含这两个元素的数组

我会试着在某个时候用node.js, Python和Perl测试这个。

I see this question is old and has so many answers, but I'll give my penny anyway. My vote is for the javascript solution on the form's 'submit' event, as some has pointed out. No doubling the inputs (especially if you have long names and attributes with php code mixed with html), no server side bother (that would require to know all field names and to check them down one by one), just fetch all the unchecked items, assign them a 0 value (or whatever you need to indicate a 'not checked' status) and then change their attribute 'checked' to true

    $('form').submit(function(e){
    var b = $("input:checkbox:not(:checked)");
    $(b).each(function () {
        $(this).val(0); //Set whatever value you need for 'not checked'
        $(this).attr("checked", true);
    });
    return true;
});

这样你会得到一个像这样的$_POST数组:

Array
(
            [field1] => 1
            [field2] => 0
)

Checkboxes usually represent binary data that are stored in database as Yes/No, Y/N or 1/0 values. HTML checkboxes do have bad nature to send value to server only if checkbox is checked! That means that server script on other site must know in advance what are all possible checkboxes on web page in order to be able to store positive (checked) or negative (unchecked) values. Actually only negative values are problem (when user unchecks previously (pre)checked value - how can server know this when nothing is sent if it does not know in advance that this name should be sent). If you have a server side script which dynamically creates UPDATE script there's a problem because you don't know what all checkboxes should be received in order to set Y value for checked and N value for unchecked (not received) ones.

由于我在数据库中存储值“Y”和“N”,并通过页面上的选中和未选中复选框表示它们,我为每个值(复选框)添加了“Y”和“N”值的隐藏字段,然后使用复选框进行可视化表示,并使用简单的JavaScript函数check()来根据选择设置if的值。

<input type="hidden" id="N1" name="N1" value="Y" />
<input type="checkbox"<?php if($N1==='Y') echo ' checked="checked"'; ?> onclick="check(this);" />
<label for="N1">Checkbox #1</label>

使用一个JavaScript onclick监听器和调用函数check()在我的网页上的每个复选框:

function check(me)
{
  if(me.checked)
  {
    me.previousSibling.previousSibling.value='Y';
  }
  else
  {
    me.previousSibling.previousSibling.value='N';
  }
}

这样,“Y”或“N”值总是发送到服务器端脚本,它知道什么是应该更新的字段,没有必要将复选框“上”值转换为“Y”或未接收复选框转换为“N”。

注意:空格或新行也是兄弟姐妹,所以这里我需要。previoussibling . previoussibling .value。如果没有空格,则只有.previousSibling.value


你不需要像以前那样显式地添加onclick监听器,你可以使用jQuery库动态添加点击监听器函数来更改页面中所有复选框的值:

$('input[type=checkbox]').click(function()
{
  if(this.checked)
  {
    $(this).prev().val('Y');
  }
  else
  {
    $(this).prev().val('N');
  }
});