I somewhat have what I wish to do working but with one problem: it performs my btnSave function for each number of input elements that change. Here is my code:
$('#base-stats').on('change', 'input', function(){
$('#btn-save').bind('click', btnSave);
});
function btnSave(){
var valid = 1;
character.currentChar.charName = $('#charName').val();
character.currentChar.charLevel = $('#charLevel').val();
character.currentChar.charLife = $('#charLife').val();
character.currentChar.charES = $('#charES').val();
character.currentChar.charInt = $('#charInt').val();
character.currentChar.charStr = $('#charStr').val();
character.currentChar.charDex = $('#charDex').val();
$('#base-stats input').each(function(){
if ($(this).val().length <= 0) {
console.log('Null field found at '+$(this).attr('id'));
$('#btn-save').unbind('click', btnSave);
valid = 0;
}
});
if (valid) {
$.post('checkchar.php',
{c:character.currentChar.charName},
function(data){
if (data == 'null') {
$.post('savechar.php',
{c:character.currentChar},
function(data){
alert('Character successfully saved to the database.');
}
);
}
else {
if (confirm('Duplicate character name exists in the database! Overwrite current character?')) {
$.post('savechar.php',
{c:character.currentChar},
function(data){
alert('Character successfully updated in the database.');
}
);
}
}
}
);
}
}
So the way it currently works, my "save button" div begins without anything bound to it, then when a form input field changes it binds my btnSave handler function to the div when I click it. So to illustrate my issue, lets say I input two values into 2 of my 7 input fields. The console then logs the 5 empty fields twice over since two fields changed:
Null field found at charLife global.js:80
Null field found at charES global.js:80
Null field found at charInt global.js:80
Null field found at charStr global.js:80
Null field found at charDex global.js:80
Null field found at charLife global.js:80
Null field found at charES global.js:80
Null field found at charInt global.js:80
Null field found at charStr global.js:80
Null field found at charDex global.js:80
How can I prevent this from happening and still ensure no null fields are posted to my server? OR should I use a different method such as checking the null array values in my savechar.php
file? I'd prefer to minimize interaction with the server though to save time.