尽管未选中,但 HTML 复选框值仍提交 (PHP)

HTML checkbox value submitting despite not being checked (PHP)

本文关键字:提交 PHP 复选框 HTML      更新时间:2023-09-26

我真的不敢相信这么简单的事情会引起如此头疼。

<input type='checkbox' name="phoneConsent" id="phoneConsent" value="1">

无论是否选中此复选框,它仍然会发布 phoneConsent 的值"1"——它不应该发布任何内容吗?

我认为这就是问题所在:

// variables for data
$(this).find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();
        // load loaded variables into array
        form_data[name] = value;

    });

如何指定未设置的复选框不应发布其值?

.php:

        $phoneConsent = (isset($_POST['phoneConsent'])) ? 1 : 0;
        // Set up the data that is headed to the table
        $data = Array(               
            'phoneConsent'   => $phoneConsent
        );

实际的网页

<div class = "form-group">
                <label for="phoneConsent" class='checkbox-inline <?php echo ($this_user[0]['subscription'] == 1 ? '' : 'disabledClass') ;?>'>
                    <input type='checkbox' name="phoneConsent" id="phoneConsent" value="1" <?php echo ($this_user[0]['phoneConsent'] == 1 ? ' checked ' : '') ;?> <?php echo ($this_user[0]['subscription'] == 1 ? '' : ' disabled ') ;?>>
                    Premium account holders: check this box to post your phone number to your teaching profile.
                </label>
            </div>

整个网页表单

<form method="post" class = "multi-form teacher_account_form" id="personal_form" name="personal_form">
            <div class ="form-group">
                <label for="country">What country are you from?</label>
                <!-- for selecting the country from db -->
                <div id = "countryfromdb" class = "hidden"><?=$this_user[0]['country_prefix'];?></div>
                <?php $form->select("country", "country_list") ;?>
            </div>
            <div class = "form-group">
                <label for="chinese_name">What is your Chinese name?</label>
                <input type = "text" class="form-control" name="chinese_name" id="chinese_name" value="<?=$this_user[0]['chinese_name']?>">
            </div>
            <div class = "form-group">
                <label for="phone">What is your phone number?*</label>
                <input type="text" class="form-control bfh-phone" data-format="+86 ddd dddd dddd" name="phone" id="phone" value="<?=$this_user[0]['phone']?>">
            </div>
            <div class = "form-group">
                <label for="phoneConsent" class='checkbox-inline <?php echo ($this_user[0]['subscription'] == 1 ? '' : 'disabledClass') ;?>'>
                    <input type='checkbox' name="phoneConsent" id="phoneConsent" <?php echo ($this_user[0]['phoneConsent'] == 1 ? ' checked ' : '') ;?> <?php echo ($this_user[0]['subscription'] == 1 ? '' : ' disabled ') ;?>>
                    Premium account holders: check this box to post your phone number to your teaching profile.
                </label>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-default btn-med account_submit" id="personal_submit" name="personal_submit">Update Personal</button>
            </div>
            <small style="color:red;">*Your phone number will NOT appear on your public profile without your permission.</small>
        </form>

jQuery

  var which_button;
//$('.account_submit').click(function() {
$('form.teacher_account_form').on('submit', function(e) {
    e.preventDefault();
    which_button = $(this).attr('id');
    // Create empty jQuery objects -
    var $jsOutput = $([]);
    var $jsForm = $([]);
    // url to submit to
    var ajaxURL = "/users/p_teacher_account_work";
    // Assign jQuery selector objects
    switch (which_button) {
        case "pay_form":
            $jsOutput = $('#pay_output');
            $jsForm = $('#pay_form');
            break;
        case "edu_form":
            $jsOutput = $('#edu_output');
            $jsForm = $('#edu_form');
            break;
        case "image_form":
            $jsOutput = $('#image_output');
            $jsForm = $('#image_form');
            break;
        case "personal_form":
            $jsOutput = $('#personal_output');
            $jsForm = $('#personal_form');
            break;
    }
    // empty data object
    var form_data = {};
    // variables for data
    $(this).find('[name]').each(function(index, value) {
        var that = $(this),
            name = that.attr('name'),
            value = that.val();
        // load loaded variables into array
        form_data[name] = value;

    });
    $.ajax({
        type: 'post',
        url: ajaxURL,
        data: form_data,
        beforeSend: function() {
            //Display a loading message while waiting for the ajax call to complete
            $jsOutput.html("Updating...");
        },
        success: function(response) {
            $jsOutput.html(response);
        }
    });
    return false;

});

控制台.log表单输出

复选框已选中

 Object {country: "AI", chinese_name: "", phone: "+86 1", phoneConsent: "on", personal_submit: ""} teacher_account.js:130

复选框未选中

Object {country: "AI", chinese_name: "", phone: "+86 1", phoneConsent: "on", personal_submit: ""} teacher_account.js:130

代码终于起作用了。我非常感激。更新的jQuery:

$(this).find('[name]').each(function(index, value) {
        var that = $(this);
        if(that.is(':checkbox'))
        {
            if(that.is(':checked'))
            {
                var name = that.attr('name');
            }
        }
        else
        {
            name = that.attr('name');
        }
            var value = that.val();
        // load loaded variables into array
        form_data[name] = value;

    });

问题出在 jQuery .ajax() 处理程序中。在"自然"表单提交中,复选框不会被发布,但您在自己收集表单数据后通过 ajax 自己进行发布。

在此:

// variables for data
$(this).find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();
    // load loaded variables into array
    form_data[name] = value;
});

您正在选择具有['name']的所有内容,并在form_data[]
上分配其值该复选框同时具有名称和值,因此无论是否选中该框,您都将 name:value 对放入form_data。

紧接着,您执行:

    $.ajax({
        type: 'post',
        url: ajaxURL,
        data: form_data,
     ...(etc)

您将data: form_data作为帖子正文发送的位置,其中包括复选框"phoneConsent:1"对。

为避免这种情况,您必须更智能地处理控件,检查输入控件类型并仅在控件checked时发送复选框(或单选按钮)数据。

试试这个代码块:

<html>
<head>
<title></title>
</head>
<?
if(isset($_POST['phoneConsent'])){
echo $_POST['phoneConsent'];
}
?>
<body bgcolor="#FFFFFF">
  <form method="post" action="test.php">
    <input type='checkbox' name="phoneConsent" id="phoneConsent" value="1">
    <input type="submit" />
  </form>
</body>

</html>

我认为您在 html 的这一部分之外的其他地方遇到了问题。

检查值是否设置,而不是值本身。无论它是否未经检查或是否按照我的记忆发送,它都会被发送。

改变 $phoneConsent = (isset($_POST['phoneConsent'])) ? 1 : 0;

if(isset($_POST['phoneConsent'])) $phoneConsent = $_POST['phoneConsent']) == '1' ? 1 : 0;