How can I make my function such that it only sends data when I have something filled out in the input fields? I have a standard of 4 input fields, whenever I insert data in 2 input fields it will send 2 words into my array (that works), but it also sends 2 empty strings. I however want the array to only exist with values and not empty strings. a quick example: You as a user decide to fill out 2 of the 4 input fields (because they are optional). I now want to prevent the 2 other input fields to send an empty string to my JSON aswell. So only what the user has filled out should be part of the array.
This is how my function looks in order to create the input fields for my array:
function getWordPartInput(id, cValue) {
console.log(cValue);
cValue = cValue || '';
var div = $('<div/>');
for (let i = 0; i < 4; i++) {
var wpInput = $('<input/>', {
'class': 'form-group form-control syllable syl ' + TT ++,
'type': 'text',
'value': (cValue[i] !== undefined) ? cValue[i] : '',
'placeholder': 'Syllables',
'name': 'Syllablescounter['+ i +']'
});
div.append(wpInput);
}
return div;
}
This is the AJAX call:
function saveExerciseAjaxCall() {
console.log(setMainObjectArray());
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
getExerciseTitle: $('#getExerciseTitle').val(),
language: $('#languageSelector').val(),
application: 'lettergrepen',
'main_object': {
title: $('#getExerciseTitle').val(),
language: $('#languageSelector').val(),
exercises: setMainObjectArray()
},
dataType: 'json'
}
}).done(function(response) {
}).fail(function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
console.log(errorThrown);
console.log(textStatus);
});
}
How setMainObjectArray() looks like:
I am talking about the array syllables.
function setMainObjectArray() {
var exercises = [];
var eBlocks = $('.eBlock');
eBlocks.each(function(i, eBlock) {
var exObject = {
word: $(eBlock).find('input.ExerciseGetWordInput').val(),
syllables: []
};
$(eBlock).find('input.syllable').each(function(j, syll) {
exObject.syllables.push($(syll).val());
});
exercises.push(exObject);
});
return exercises;
}
setMainObjectArray()? Need to know what this function does then.