【问题标题】:HTML checkbox value submitting despite not being checked (PHP)尽管未检查,但仍提交 HTML 复选框值(PHP)
【发布时间】:2014-04-04 21:06:44
【问题描述】:

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

<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
        );

实际的 HTML

<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>

整个 HTML 表单

<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;


});

console.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;


    });

【问题讨论】:

  • 我刚刚将您的代码粘贴到我的服务器上,它就像一个魅力检查它自己 robyapps.com/prova.php 我只需要删除国家/地区选择方法,因为我没有那个 php 功能
  • @verdesrobert 也许我们应该交易电脑,我准备把我的电脑扔出窗外
  • 把 print_r($_POST);在您的 php 中查看您收到的内容
  • @verdesrobert 自 AJAX 以来,我将表单数据打印到控制台。我刚刚在上面添加了控制台输出:与您的服务器不同,在我的服务器上,每当我提交表单时,它都会发布复选框是否选中
  • 您使用的是什么版本的 jquery?在我的页面中,我使用了谷歌最新的 jquery 版本,也许这也有所不同

标签: javascript html forms


【解决方案1】:

问题出在您的 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 时发送复选框(或单选按钮)数据。

【讨论】:

  • 非常感谢——我完全同意——知道我如何只发送检查过的输入吗?
  • 如果您浏览我发送给您的页面的代码,您会发现这不是问题
  • 知道如何保留我将名称/值对分配给 JS 对象的方法,但现在能够处理同名“复选框 []”的多个复选框。 ?由于我为名称分配了一个值,因此我只能得到最后一个同名复选框。
【解决方案2】:

试试这个代码块:

<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 的这一部分之外的其他地方有问题。

【讨论】:

    【解决方案3】:

    您检查是否设置了值,而不是值本身。据我所知,无论是否未选中都会发送。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 2020-01-14
      • 2019-06-25
      • 2014-06-26
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      相关资源
      最近更新 更多