尽管没有被检查,HTML复选框值提交(PHP)

时间:2014-04-04 21:06:45

标签: javascript html forms

我真的不敢相信这么简单的东西引起如此头疼。

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


    });

3 个答案:

答案 0 :(得分: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[]上指定其值 复选框 同时具有名称和值,因此无论是否选中该框,都要在form_data中放置name:value对。

紧接着,你做了:

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

您要将data: form_data作为帖子正文发送,其中包含“phoneConsent:1”对复选框。

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

答案 1 :(得分:0)

试试这段代码:

<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的这一部分。

答案 2 :(得分:0)

检查是否设置了值,而不是值本身。无论是否记不清,它都会被发送。

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

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