So, I have a JSON file which I fetch. The array syllables
can hold up to a max. of 4 strings. However, when I leave out (for example) 2 words, I will end up with 2 words and 2 empty strings. However in my front-end when I try to create a check it will still require 4 "strings". So 2 words + 2 times the key "enter" before it says that the length
equals my JSON. However I want empty strings NOT to be part of the length
. I have this to trim the length, but I don't know why it doesn't work.
The code:
var correctSylls = [];
$.map(exercise.syllables, function (syllable, j) {
// Code to check if the syllable exists and is not an empty string
if (!syllable || !syllable.filter(str => str != "").length) {
// If it doesn't exist or is an empty string, return early without creating/appending elements
return;
}
var innerSylCol = $('<div/>', {
class: 'col-md-3 inputSyllables'
});
var sylInput = $('<input/>', {
'type': 'text',
'class': 'form-control syl-input',
'name': +c++,
'id': +idsyll++
}).on('keyup', function() {
var cValue = $(this).val();
if (cValue === syllable) {
correctSylls.push(cValue);
console.log(correctSylls);
}
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').addClass('btn btn-success').removeClass('form-control');
}
});
Right now this piece prevents me from going further:
if (!syllable || !syllable.filter(str => str != "").length) {
with the above code the next error is thrown in:
Uncaught TypeError: syllable.filter is not a function.
But I do call it in my $(document).ready
function (This is one big function called createExercise
).
I do call the function:
$(document).ready(function () {
$.getJSON('json_files/jsonData_' + ID + '.json', function(json) {
createExercise(json);
});
}
Now let's say this is my fault and this does the right thing. My main problem will remain: How can I create this part:
if (exercise.syllables.length === correctSylls.length) {
$(this).closest('.syll-row').find('input.syl-input').addClass('btn btn-success').removeClass('form-control');
}
so it will ONLY check the value filled out equals the length in my JSON without considering empty strings as a value aswell?
Example: I have in my array of syllables
only one word and 3 empty strings. The code above loops through my JSON aswell and creates input fields, so it creates one input field. I now insert that one single word. But according to my check it doesn't contain the same length, because it still has 3 empty strings. Therefore I have to press enter 3 times before it reaches the correct length and changes the background color to green.
The variable exercise
holds the value: json.main_object.main_object.exercises;
in case anyone wonders.