【问题标题】:JQuery not setting variable when checkbox is checked选中复选框时JQuery未设置变量
【发布时间】:2019-07-09 02:35:43
【问题描述】:

这很简单,但我看不出我的错误。当用户单击复选框时,变量 isEmployee 需要设置为 true。然后我将该变量传递给 JSON 数组,但出于某种原因,无论我做什么,都没有设置 isEmployee 变量。

<label for="EmployStats">Current Employee: </label><input type="checkbox" id="EmployStats" checked />

var isEmployee = false;
$('#EmployStats').change(function()
{
     if(this.checked)
     {
        isEmployee = true;
     }
});

data = {'Employ_Status':isEmployee};  

但是,当我点击提交按钮时,即使单击了复选框,标题仍将 Employ_Status 显示为 false。

我一辈子都看不出这有什么问题

更新:设置复选框后设置数据数组的原因是数据数组仅在其他字段验证后才提交:

if(submit == true) { //If data is present, then prepare email and user values to be submitted to .php page
    var results;
    data = {
       'Employ_name': $('#EmployName').val(),
       'Employ_num': $('#EmployNumber').val(),
       'Employ_phone': $('#Phone').val(),
       'Employ_address': $('#Address').val(),
       'Employ_city': $('#City').val(),
       'Employ_state': $('#State').val(),
       'Employ_zip': $('#Zip').val(),
       'Employ_Status':isEmployee
    }; //Add input to JSON array

    //post data via ajax to success.php and retrieve response
    $.post("success.php", data, function(ReturnedData) {
        if(ReturnedData.Type == 'Error') { //If error returned, display error message
            results = '<h1 class="error">'+ReturnedData.Message+'</h1>';
        } else if (ReturnedData.Type == 'Success') { //If success returned, display message and remove submit button
            results = '<h1 class="success">'+ReturnedData.Message+'</h1>';
        }
        $('#DataHolder').html(results);
    }, 'json');
});

更新 #2。好的,让大家看看我从头到尾都在做什么:

<!DOCTYPE HTML>
<HEAD>
    <TITLE>Jeremy's Form Submit Test </TITLE>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <link rel="stylesheet" type="text/css" href="css/form_submit.css">
    <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
    <script src="js/form_submit.js"></script>
</HEAD>
<BODY>
    <div id="MainForm">
    <label for="EmployName">*Employee Name: </label><input type="text" id="EmployName"  /> 
    <label for="EmployNumber">*Employee Number: </label><input type="text" id="EmployNumber"  /> 
    <label for="Phone">*Phone Number: </label><input type="text" id="Phone"  /> 
    <label for="Address">*Address: </label><input type="text" id="Address"  />
    <label for="City">*City: </label><input type="text" id="City" />
    <label for="State">*State </label>
    <select id="State">
        <option value="" selected="selected">Select a State</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>    
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="DE">Delaware</option>
        <option value="DC">District Of Columbia</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="HI">Hawaii</option>
        <option value="ID">Idaho</option>
        <option value="IL">Illinois</option>
        <option value="IN">Indiana</option>
        <option value="IA">Iowa</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="ME">Maine</option>
        <option value="MD">Maryland</option>
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="MN">Minnesota</option>
        <option value="MS">Mississippi</option>
        <option value="MO">Missouri</option>
        <option value="MT">Montana</option>
        <option value="NE">Nebraska</option>
        <option value="NV">Nevada</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NM">New Mexico</option>
        <option value="NY">New York</option>
        <option value="NC">North Carolina</option>
        <option value="ND">North Dakota</option>
        <option value="OH">Ohio</option>
        <option value="OK">Oklahoma</option>
        <option value="OR">Oregon</option>
        <option value="PA">Pennsylvania</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="SD">South Dakota</option>
        <option value="TN">Tennessee</option>
        <option value="TX">Texas</option>
        <option value="UT">Utah</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WA">Washington</option>
        <option value="WV">West Virginia</option>
        <option value="WI">Wisconsin</option>
        <option value="WY">Wyoming</option>
    </select>
    <label for="Zip">*Zip: </label><input type="text" id="Zip" /> 
    <label for="EmployStats">Current Employee: </label><input type="checkbox" id="EmployStats" checked />
    <input type="submit" id="FormSubmit" value="Submit">
</div>

<div id="DataHolder"></div>
</BODY>
</HTML>

表单提交到的 PHP 脚本:

<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest')) { //Make sure it's not a direct request. Must be ajax
    $ReturnedData = json_encode(array("Type" => "Error", "Message" => "Naughty, Naughty. This must be an ajax request!!!"));
    die($ReturnedData);
}
if(isset($_POST)) { //Ensure that POST is set
    //Santiaze the post variables to be double sure no one is up to any funky business
    $SaniUser = filter_var($_POST['Employ_name'],FILTER_SANITIZE_STRING);
    $SaniNum = filter_var($_POST['Employ_num'],FILTER_SANITIZE_NUMBER_INT);
    $SaniPhone = filter_var($_POST['Employ_phone'],FILTER_SANITIZE_NUMBER_INT);
    $SaniAddress= filter_var($_POST['Employ_address'],FILTER_SANITIZE_STRING);
    $SaniCity = filter_var($_POST['Employ_city'],FILTER_SANITIZE_STRING);
    $SaniState = filter_var($_POST['Employ_state'],FILTER_SANITIZE_STRING);
    $SaniZip = filter_var($_POST['Employ_zip'],FILTER_SANITIZE_NUMBER_INT);

    //Get Employee Status
    $SaniEmploy = $_POST['Employ_Status'];

    if ($SaniEmploy != "true") {
        $ReturnedData = json_encode(array("Type" => "Success", "Message" => "Hello  " .$SaniUser. " . Thank you for submitting your information. Your employee number is ".$SaniNum . " . You Phone number is ".$SaniPhone. " . You live at " .$SaniAddress. " in " .$SaniCity. " from " .$SaniState. "in the " .$SaniZip. ". You're currently NOT an employee!!!"));
        die($ReturnedData);
    } else {    
        $ReturnedData = json_encode(array("Type" => "Success", "Message" => "Hello  " .$SaniUser. " . Thank you for submitting your information. Your employee number is ".$SaniNum . " . You Phone number is ".$SaniPhone. " . You live at " .$SaniAddress. " in " .$SaniCity. " from " .$SaniState. "in the " .$SaniZip. ". You're currently an employee!!!"));
        die($ReturnedData);
    }

} else {
    $ReturnedData = json_encode(array("Type" => "Error", "Message" => "Naughty naughty. No data was submitted!!!"));
    die($ReturnedData);
}

?>

这是执行所有检查的完整 jquery

$(document).ready(function() {
    $("#FormSubmit").click(function() { //Set click action on formsubmit button
        var submit = true; //Set default status on submit button
        var isEmployee = false;

        if($.trim($('#EmployName').val()) == '') { //Remove whitespaces and check if field is empty
             alert('Employee Name can not be blank');
             submit = false;
        }
        var Num = /^[\d]+$/; //RegEx to ensure it's a number being submitted
        if($.trim($('#EmployNumber').val()) == '' || !Num.test($.trim($('#EmployNumber').val()))) { //Remove whitespaces and check if field is number
             alert('Employee Number can not be blank and it must be a number');
             submit = false;
        }

        var Phoneregex = /^1?[\s-]?\(?(\d{3})\)?[\s-]?\d{3}[\s-]?\d{4}$/; //RegEx to test phone number against
        if(!Phoneregex.test($.trim($('#Phone').val()))) { //If supplied email without whitespaces doesn't match pattern, then alert user
            alert('Please provide a valid phone number. You must include the dashes');
            submit = false;
        }

        if($.trim($('#Address').val()) == '') { //Remove whitespaces and check if field is empty
            alert('Address can not be blank');
            submit = false;
        }

        if($.trim($('#City').val()) == '') { //Remove whitespaces and check if field is empty
             alert('City can not be blank');
             submit = false;
         }

         if($('#State').val() == '') { //Remove whitespaces and check if field is empty
             alert('Please select a state from the dropdown menu');
             submit = false;
         }

         if($.trim($('#Zip').val()) == '' || !Num.test($.trim($('#Zip').val()))) { //Remove whitespaces and check if field is number
             alert('Zip can not be blank and it must be a number');
             submit = false;
         }
         $('#EmployStats').change(function() {
             if(this.checked) {
                 isEmployee = true;
                 data['Employ_Status'] = isEmployee;
             }
         });

         if(submit == true) { //If data is present, then prepare email and user values to be submitted to .php page
             var results;
             data = {
                 'Employ_name': $('#EmployName').val(),
                 'Employ_num': $('#EmployNumber').val(),
                 'Employ_phone': $('#Phone').val(),
                 'Employ_address': $('#Address').val(),
                 'Employ_city': $('#City').val(),
                 'Employ_state': $('#State').val(),
                 'Employ_zip': $('#Zip').val(),
                 'Employ_Status':isEmployee
             }; //Add input to JSON array

             $.post("success.php", data, function(ReturnedData) { //post data via ajx to success.php and retrieve response
                 if(ReturnedData.Type == 'Error') { //If error returned, display error message
                     results = '<h1 class="error">'+ReturnedData.Message+'</h1>';
                 } else if (ReturnedData.Type == 'Success') { //If success returned, display message and remove submit button          
                     results = '<h1 class="success">'+ReturnedData.Message+'</h1>';
                 }
                 $('#DataHolder').html(results);
             }, 'json');
         }
     });
});

更新 #3

最终的工作代码如下。由于我没有将 isEmployee 声明为全局变量。

$(document).ready(function() {
    var data; //Declare data object to hold values
    var isEmployee = false; //Declare isEmployee which will store checkbox value
    $('#EmployStats').change(function() {
        if(this.checked) {
            isEmployee = true;
        } else {
            isEmployee = false;
        }
    });

    $("#FormSubmit").click(function() { //Set click action on formsubmit button
        var submit = true; //Set default status on submit button
        if($.trim($('#EmployName').val()) == '') { //Remove whitespaces and check if field is empty
            alert('Employee Name can not be blank');
            submit = false;
        }

        var Num = /^[\d]+$/; //RegEx to ensure it's a number being submitted
        if($.trim($('#EmployNumber').val()) == '' || !Num.test($.trim($('#EmployNumber').val()))) { //Remove whitespaces and check if field is number
             alert('Employee Number can not be blank and it must be a number');
             submit = false;
         }

         var Phoneregex = /^1?[\s-]?\(?(\d{3})\)?[\s-]?\d{3}[\s-]?\d{4}$/; //RegEx to test phone number against
         if(!Phoneregex.test($.trim($('#Phone').val()))) {  //If supplied email without whitespaces doesn't match pattern, then alert user
             alert('Please provide a valid phone number. You must include the dashes');
             submit = false;
         }

         if($.trim($('#Address').val()) == '') { //Remove whitespaces and check if field is empty
             alert('Address can not be blank');
             submit = false;
         }

         if($.trim($('#City').val()) == '') { //Remove whitespaces and check if field is empty
             alert('City can not be blank');
             submit = false;
         }

         if($('#State').val() == '') { //Remove whitespaces and check if field is empty
             alert('Please select a state from the dropdown menu');
             submit = false;
         }

         if($.trim($('#Zip').val()) == '' || !Num.test($.trim($('#Zip').val()))) { //Remove whitespaces and check if field is number
              alert('Zip can not be blank and it must be a number');
              submit = false;
         }

         if(submit == true) { //If data is present, then prepare email and user values to be submitted to .php page
             var results;
             data = {
                 'Employ_name': $('#EmployName').val(),
                 'Employ_num': $('#EmployNumber').val(),
                 'Employ_phone': $('#Phone').val(),
                 'Employ_address': $('#Address').val(),
                 'Employ_city': $('#City').val(),
                 'Employ_state': $('#State').val(),
                 'Employ_zip': $('#Zip').val(),
                 'Employ_Status':isEmployee
             }; //Add input to JSON array

             $.post("success.php", data, function(ReturnedData) { //post data via ajx to success.php and retrieve response
                 if(ReturnedData.Type == 'Error') { //If error returned, display error message
                     results = '<h1 class="error">'+ReturnedData.Message+'</h1>';
                 } else if (ReturnedData.Type == 'Success') { //If success returned, display message and remove submit button
                     results = '<h1 class="success">'+ReturnedData.Message+'</h1>';
                 }
                 $('#DataHolder').html(results);
             }, 'json');
         }
     });
 });

【问题讨论】:

  • 数据正在事件处理程序之外设置。尝试在更改回调中移动它。

标签: javascript jquery checkbox


【解决方案1】:

你需要把你的声明放在函数里面:

$('#EmployStats').change(function()
{
     if(this.checked)
     {
        isEmployee = true;
      }

     // this has to be modified as well on every change
     data = {'Employ_Status':isEmployee};  
});

您也可以将代码修改为更简洁:

$('#EmployStats').change(function()
{
     isEmployee = this.checked;

     // this has to be modified as well on every change
     data['Employ_Status'] = isEmployee;
});

编辑:将data = {'Employ_Status':isEmployee}; 更改为data['Employ_Status'] = isEmployee;,以便仅修改该对象的字段/属性

编辑:您可以通过多种方式修复它,但要改变它:

$('#EmployStats').change(function()
{
    if(this.checked)
    {
        isEmployee = true;
        data['Employ_Status'] = isEmployee;
    }
});

用这个:

if($('#EmployStats').attr("checked"))
{
    isEmployee = true;
    data['Employ_Status'] = isEmployee;
}

会修复它。这是因为每当用户单击提交按钮时,您的代码就会被执行。因此,不是将复选框值分配给data['Employ_Status'] 到true 或任何值,而是在您的复选框上设置更改的侦听器而忽略其当前值

【讨论】:

  • 第二个版本有效;第一个有一个错误:您需要添加else isEmployee = false,否则如果用户选中它然后取消选中它,它不会被设置回false。
  • 圣地亚哥,谢谢您的回复。但是,这对我不起作用的原因是数据中有其他值。在我验证所有输入并构建 json 数组之前,数据尚未完全设置
  • @Matt Browne 是正确的;吉米检查我所做的编辑
  • 另一个提示,并不是说它有很大的不同...请注意data.Employ_Status = isEmployee; 也可以。
  • @Matt Browne 是的,这是访问对象字段/属性的另一种方式,谢谢 ;)
【解决方案2】:

我已经测试了您的代码,看来isEmployee DO 正确切换了它的值。如果您的问题是您的数据对象没有相应地更新,那仅仅是因为您没有将它放在更改事件中。因此,它只会在第一次定义。要解决此问题,您可以尝试以下示例:

HTML

<label for="EmployStats">Current Employee: </label><input type="checkbox" id="EmployStats" checked />
<div id="kanban"></div>

JS

var isEmployee = false;
var data = {'Employ_Status':isEmployee};  

$('#EmployStats').change(function()
{
     if(this.checked)
     {
        isEmployee = true;
     } else {
         isEmployee = false;
     }

    data.Employ_Status = isEmployee;
    $('#kanban').html(data.Employ_Status.toString());
});

这里是the example。

如果不是这种情况,我认为问题出在您的表单提交过程中。能否提供更详细的整个流程代码?


编辑

现在很明显,导致此问题的原因是您的 isEmployee 没有切换它的值。

这是你的代码:

// ...

$('#EmployStats').change(function()
{
  if(this.checked)
  {
    isEmployee = true;
    data['Employ_Status'] = isEmployee;
  }
});

// ...

如您所见,第一次选中#EmployStats 时,它会将isEmployee 设置为true,但是当用户第二次单击复选框时,它无法切换回来。要在此处设置切换条件,您可以尝试:

$('#EmployStats').change(function()
{
  if(this.checked)
  {
    isEmployee = true;
  } 
  else 
  {
    isEmployee = false;
  }

  data['Employ_Status'] = isEmployee;

});

编辑

这是您的代码的进一步重构版本:

$(document).ready(function() {
  // Prepare your data object outside your event handler
  var data = data || {};

  // Move your checkbox event handler out from submit event
  $('#EmployStats').change(function() {
    isEmployee = (this.checked) ? true : false;    
    data['Employ_Status'] = isEmployee;
  });

  // Your original submit event handler
  $("#FormSubmit").click(function() {
    ...
  });

});

【讨论】:

  • 感谢您的回复。我已经用我目前正在提交/验证/响应的所有 3 个文件更新了帖子
  • 您好,感谢您的回复。但即使我添加了您的代码,无论复选框被选中,employ_status 仍被设置为 false
  • 把这个代码块从$("#FormSubmit").click(function() { ... });移出怎么样?实际上,您不需要在单击提交按钮时绑定 onChange 事件处理程序。然后,您甚至可以将您的数据对象移出整个 click handler 以保持其状态。检查新示例。
  • 我没有看到新的例子。再次感谢
  • 这个问题是根本没有发布employee_status。它不再出现在标题中
【解决方案3】:

尝试在更改事件中设置数据。

var isEmployee = false;var data;

$('#EmployStats').change(function()
{
     if(this.checked)
     {
        isEmployee = true;
      }else{
        isEmployee = false;
        }
  data = {'Employ_Status':isEmployee};
  alert(data['Employ_Status']);
// now pass it where you want
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="EmployStats">Current Employee: </label><input type="checkbox" id="EmployStats" />

// 使用 isEmployee 点击提交,如下所示:

var isEmployee = false;var data;

$('#EmployStats').change(function()
{
     if(this.checked)
     {
        isEmployee = true;
      }else{
        isEmployee = false;
        }

  alert(isEmployee);
});
 $("#FormSubmit").click(function() //Set click action on formsubmit button
        {
                var submit = true; //Set default status on submit button

                                if($.trim($('#EmployName').val()) == '') //Remove whitespaces and check if field is empty
                                {
                                        alert('Employee Name can not be blank');
                                        submit = false;
                                }
                                var Num = /^[\d]+$/; //RegEx to ensure it's a number being submitted
                                if($.trim($('#EmployNumber').val()) == '' || !Num.test($.trim($('#EmployNumber').val()))) //Remove whitespaces and check if field is number
                                {
                                        alert('Employee Number can not be blank and it must be a number');
                                        submit = false;
                                }

                                var Phoneregex = /^1?[\s-]?\(?(\d{3})\)?[\s-]?\d{3}[\s-]?\d{4}$/; //RegEx to test phone number against
                                if(!Phoneregex.test($.trim($('#Phone').val()))) //If supplied email without whitespaces doesn't match pattern, then alert user
                                {
                                        alert('Please provide a valid phone number. You must include the dashes');
                                        submit = false;
                                }

                                if($.trim($('#Address').val()) == '') //Remove whitespaces and check if field is empty
                                {
                                        alert('Address can not be blank');
                                        submit = false;
                                }

                                if($.trim($('#City').val()) == '') //Remove whitespaces and check if field is empty
                                {
                                        alert('City can not be blank');
                                        submit = false;
                                }

                                if($('#State').val() == '') //Remove whitespaces and check if field is empty
                                {
                                        alert('Please select a state from the dropdown menu');
                                        submit = false;
                                }

                                if($.trim($('#Zip').val()) == '' || !Num.test($.trim($('#Zip').val()))) //Remove whitespaces and check if field is number
                                {
                                        alert('Zip can not be blank and it must be a number');
                                        submit = false;
                                }


                                if(submit == true) //If data is present, then prepare email and user values to be submitted to .php page
                                {
                                        var results;
                                        data = {'Employ_name': $('#EmployName').val(), 'Employ_num': $('#EmployNumber').val(), 'Employ_phone': $('#Phone').val(), 'Employ_address': $('#Address').val(), 'Employ_city': $('#City').val(), 'Employ_state': $('#State').val(),'Employ_zip': $('#Zip').val(), 'Employ_Status':isEmployee}; //Add input to JSON array
                                        $.post("success.php", data, function(ReturnedData) //post data via ajx to success.php and retrieve response
                                        {
                                                if(ReturnedData.Type == 'Error') //If error returned, display error message
                                                {
                                                        results = '<h1 class="error">'+ReturnedData.Message+'</h1>';
                                                }
                                                else if(ReturnedData.Type == 'Success') //If success returned, display message and remove submit button
                                                {

                                                        results = '<h1 class="success">'+ReturnedData.Message+'</h1>';
                                                }
                                                $('#DataHolder').html(results);
                                        }, 'json');
                                }
        });

【讨论】:

  • 您好,感谢您的回复。这里的问题是警报确实会提醒正确的状态。但是 Employ_Status 的传递根本没有设置
  • 您好,问题是,'Employ_Status 正在您的更改函数中设置,但是当您发布数据时{},Employ_status 未定义。由于某种原因,完整数据的帖子{}丢失了在更改函数中设置的 Employ_Status
  • 问题在于您设置数据的逻辑。您正在尝试在单击提交内触发更改事件,因此它将不起作用。全局声明 isEmployee 并在更改复选框时重新为其分配值,并在提交时使用此值发布。我将编辑答案。
  • 如果您有任何问题,请告诉我。
  • 如果我能穿过这个屏幕亲吻你,我会的。谢谢谢谢谢谢你!!!
猜你喜欢
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 2014-09-06
  • 2018-01-27
  • 2022-11-24
  • 1970-01-01
  • 2012-06-29
相关资源
最近更新 更多