mardi 28 avril 2015

JQuery not setting variable when checkbox is checked

Howdie do,

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




Aucun commentaire:

Enregistrer un commentaire