Reputation: 881
It's very simple, but I can't see my mistake. When the user clicks the checkbox, the variable isEmployee needs to be set to true. I then pass that variable to a JSON array, but some reason, no matter what I do, the isEmployee variable isn't being set.
<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};
However, when I hit my submit button, the header still is showing Employ_Status as false even when the checkbox is clicked.
I can't for the life of me see what is wrong with this
UPDATE: The reason the data array is set after the checkbox being set is due to the data array only being submitted after other fields have been validated:
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');
});
UPDATE #2. Ok so for everyone to see what I'm doing from beginning to end:
<!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>
The PHP script that the form is submitted to:
<?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);
}
?>
This is the full jquery that is doing all of the checking
$(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');
}
});
});
UPDATE #3
The final working code is below. Due to me not declaring isEmployee as a global variable.
$(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');
}
});
});
Upvotes: 0
Views: 300
Reputation: 11859
Try like this set data inside change event.
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" />
// use isEmployee on click to submit like this:
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');
}
});
Upvotes: 1
Reputation: 1806
I've tested your code and it seems the isEmployee
DO toggle its value correctly. If your problem is that your data object is not updating accordingly, that's simply because you didn't put that inside your change event. Thus, it will only be defined at the first time. To fix that, you can try the following example:
<label for="EmployStats">Current Employee: </label><input type="checkbox" id="EmployStats" checked />
<div id="kanban"></div>
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());
});
Here's the example.
If this is not the case, I think the problem would be in your form submitting process. Could you provide more detailed codes about the whole process?
Now it's clear that the cause of this issue is due to your isEmployee
is not toggling it's value.
Here's your code:
// ...
$('#EmployStats').change(function()
{
if(this.checked)
{
isEmployee = true;
data['Employ_Status'] = isEmployee;
}
});
// ...
As you can see, the first time you check #EmployStats
, it would set isEmployee
to true
, but there's no way it can toggle back when users click the checkbox the second time. To set a toggle condition here, you can try:
$('#EmployStats').change(function()
{
if(this.checked)
{
isEmployee = true;
}
else
{
isEmployee = false;
}
data['Employ_Status'] = isEmployee;
});
Here's a further refactored version of your codes:
$(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() {
...
});
});
Upvotes: 2
Reputation: 5636
you need to put your declaration inside the function:
$('#EmployStats').change(function()
{
if(this.checked)
{
isEmployee = true;
}
// this has to be modified as well on every change
data = {'Employ_Status':isEmployee};
});
also you can modify your code to be a bit cleaner:
$('#EmployStats').change(function()
{
isEmployee = this.checked;
// this has to be modified as well on every change
data['Employ_Status'] = isEmployee;
});
EDIT: changed data = {'Employ_Status':isEmployee};
to data['Employ_Status'] = isEmployee;
in order to modify only that object's field/property
EDIT: you can fix it in a lot of ways, but changing this:
$('#EmployStats').change(function()
{
if(this.checked)
{
isEmployee = true;
data['Employ_Status'] = isEmployee;
}
});
with this:
if($('#EmployStats').attr("checked"))
{
isEmployee = true;
data['Employ_Status'] = isEmployee;
}
will fix it. This is because your code is being executed whenever the user click the submit button. So instead of assign the checkbox value to data['Employ_Status']
to true
or whatever the value is, is setting a change's listener on your checkbox ignoring its current value
Upvotes: 2