0

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');
 }
 });
 });
Steffen Moritz
7,75811 gold badges41 silver badges57 bronze badges
asked Apr 29, 2015 at 2:28
1
  • 1
    Data is being set outside the event handler. Try moving that inside your change callback. Commented Apr 29, 2015 at 2:30

3 Answers 3

2

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

answered Apr 29, 2015 at 2:29
Sign up to request clarification or add additional context in comments.

13 Comments

The second version works; the first has a bug: you'd need to add else isEmployee = false, otherwise it wouldn't get set back to false if the user checked it and then unchecked it.
Santiago, Thank you for your reply. However, the reason this doesn't work for me is due to the fact that data has other values in it. Data isn't fully set until I validate all input and then json array is built
@Matt Browne that's correct; jimmy check the edit that i've done
One other tip, not that it's much of a difference...note that data.Employ_Status = isEmployee; would also work.
@Matt Browne yeah it's another way to access an object's field/property, thanks ;)
|
2

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:

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

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?


Edit

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

Edit

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() {
 ...
 });
});
answered Apr 29, 2015 at 2:43

6 Comments

Thank you for your reply. I've updated the post with all 3 files that I currently have that are doing the submitting/validation/responses
Hello, Thank you for your reply. But even when I add your code, employ_status is still being set to false regardless of the checkbox being selected
How about moving this code block out from $("#FormSubmit").click(function() { ... }); ? Actually you don't need to bind onChange event handeler evert time you click submit button. Then you can even move your data object out of the whole click handler to keep it's state. Check the new example.
I do not see the new example. Thanks again
The issue with this is that the employee_status isn't being posted at all. It's no longer present in the headers
|
1

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');
 }
 });
answered Apr 29, 2015 at 2:48

5 Comments

Hello, thank you for your reply. The issue here is the alert does alert the correct status. But the passing of Employ_Status doesn't get set at all
Hello, The issue is yes, the 'Employ_Status is being set in your change function, but when you post the data{}, the Employ_status is undefined. For some reason, the post of the full data{} loses the Employ_Status that was set in the change function
the problem is in your logic of setting the data. you are trying to fire change event inside click to submit so it will not work.declare isEmployee globaly and on change of check box reassign value to it and on submit use this value to post.I'll edit the answer.
If you have any problem let me know.
If I could come through this screen and kiss, you, I would. THANK YOU THANK YOU THANK YOUUU!!!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.