When attempting to determine the length of a JavaScript list, I noticed that it returns the actual length of the list rather than the number of items within the string. Allow me to provide an example. Consider the following list:
<QuerySet [<Genre: Romance>, <Genre: Science Fiction>, <Genre: Fantasy>, <Genre: Mystery>, <Genre: Thriller>, <Genre: Horror>, <Genre: Historical Fiction>, <Genre: Biography>, <Genre: Autobiography>, <Genre: Memoir>, <Genre: Young Adult>, <Genre: Children's>, <Genre: Literary Fiction>, <Genre: Comedy>, <Genre: Business>, <Genre: Travel>, <Genre: Cookbooks>, <Genre: Poetry>, <Genre: Drama>, <Genre: Fairy-tail>]>
In my implementation, I retrieve the list as follows, where ‘genres’ represents the list:
<input type="hidden" id="genres_get" value="{{ genres }}" style="display: none;">
Getting it in Javascript
genres = document.getElementById('genres_get').value;
And trying to print the length
console.log(genres.length)
After executing the code, it incorrectly prints the value 414 instead of the expected length, which is 20.
>Solution :
The input’s value is a string, not an array. If you put an array in the value, the array will be converted to string with .toString() which will join the elements with a comma. So when you do genres.length you are using the length property of a String and not an array, so you get the number of characters in the string.
You’d certainly want to split(‘,’) the string and then count the elements.
console.log(genres.split(',').length)
Note that this is not really a good way to do it. Why are you putting the data in a hidden input in the first place? Can’t you just hold onto it in your component?