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