I'm implementing dynamic select inputs but they have an odd behavior.
There are three select inputs. The first one is to select a book title, the second input is to select initial chapter and the third is for final chapter. Each book has determined numbers of chapters.
So, when a book is selected the other inputs are emptied and populated through a for loop and when the initial chapter is selected the final chapter input is also emptied and populated through a for loop.
The problem is: when I select some initial chapter the final chapter input is emptied but not populated. The behavior is odd because it works for initial chapter 1-2, then it stops and it works again for chapters 10-end.
Script code:
$('#initial_chapter_select').change(function() {
$('#initial_chapter_select option:selected').each(function() {
selected_initial_chapter = $(this).val();
console.log('Selected initial chapter: ' + selected_initial_chapter);
console.log('Selected book last chapter: ' + selected_book_last_chapter);
$("#final_chapter_select option").remove();
console.log('Final Chapter emptied');
for (var chapter = selected_initial_chapter; chapter <= selected_book_last_chapter; chapter++) {
console.log('Loop chapter: ' + chapter);
$('#final_chapter_select').append("<option value=" + chapter + ">" + chapter + "</option>");
}
});
});
Console terminal when I select initial chapter inputs 1, 2, 3, ..., 10:
Selected initial chapter: 1
Selected book last chapter: 27
Final Chapter emptied
Loop chapter: 1
Loop chapter: 2
(...)
Loop chapter: 27
Selected initial chapter: 2
Selected book last chapter: 27
Final Chapter emptied
Loop chapter: 2
Loop chapter: 3
(...)
Loop chapter: 27
Selected initial chapter: 3
Selected book last chapter: 27
Final Chapter emptied
Selected initial chapter: 4
Selected book last chapter: 27
Final Chapter emptied
(...)
Selected initial chapter: 9
Selected book last chapter: 27
Final Chapter emptied
Selected initial chapter: 10
Selected book last chapter: 27
Final Chapter emptied
Loop chapter: 10
Loop chapter: 11
(...)
Loop chapter: 27
Adding parseInt fixed the issue...
That is because the loop also can handle string comparison, and this creates "surprising" results like below because the evaluation is done character per character... Like to sort some strings. A human would consider those as numbers... By the computer no.
Conclusion, be careful about the type of the variables you use.
console.log("22" > "3") // false!!!