JQuery 选中复选框时未设置变量
JQuery not setting variable when checkbox is checked
很简单,但是看不出我的错误。当用户单击复选框时,需要将变量 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};
但是,当我点击提交按钮时,header 仍然显示 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');
}
});
});
您需要将声明放在函数中:
$('#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;
以便仅修改该对象的 field/property
编辑: 你可以用很多方法修复它,但改变这个:
$('#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
或任何值,而是在您的复选框上设置更改的侦听器而忽略其当前值
我已经测试了您的代码,似乎 isEmployee
确实正确地切换了它的值。如果您的问题是您的数据对象没有相应更新,那只是因为您没有将其放入更改事件中。因此,它只会在第一次定义。要解决此问题,您可以尝试以下示例:
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() {
...
});
});
像这样在更改事件中设置数据。
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');
}
});
很简单,但是看不出我的错误。当用户单击复选框时,需要将变量 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};
但是,当我点击提交按钮时,header 仍然显示 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');
}
});
});
您需要将声明放在函数中:
$('#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;
以便仅修改该对象的 field/property
编辑: 你可以用很多方法修复它,但改变这个:
$('#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
或任何值,而是在您的复选框上设置更改的侦听器而忽略其当前值
我已经测试了您的代码,似乎 isEmployee
确实正确地切换了它的值。如果您的问题是您的数据对象没有相应更新,那只是因为您没有将其放入更改事件中。因此,它只会在第一次定义。要解决此问题,您可以尝试以下示例:
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() {
...
});
});
像这样在更改事件中设置数据。
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');
}
});