I'm trying to filter values from a dataset and have it reflect on a page, using JavaScript, but am struggling to get the solution.
I need it so that when I select one of the values in the select filter, the narrative will also update accordingly to the correct value (the third column) in the data.
I think I'm having trouble partly because of the way this data will be structured in these arrays (see countryData in the JS. Though optimally that's how I think it comes to me when I pull it from my data source... Will prefer to keep it like that unless anyone sees major red flags.
Extra points if you can provide separate solutions using both vanilla JS and jquery!
HTML
<div class="tab-pane fade show active" id="mapTab">
<div class="sidebar">
<div class="select">
<select id="countrySelector" class="form-select selectpicker" data-width="100%" data-size="8" name="country"
data-dropdown>
<option value="">Country</option>
<option id="all" value="All">All</option>
<option id="afg" value="Afghanistan">Afghanistan</option>
<option value="Bangladesh">Bangladesh</option>
<option value="Bhutan">Bhutan</option>
</select>
</div>
</div>
</div>
<div id="narrative"></div>
</div>
JavaScript
<script>
const countryData = new Array([
["AFG", "Afghanistan", "Test narrative about Afghanistan"],
["BGD", "Bangladesh", "Test narrative about Bangladesh"],
["BTN", "Bhutan", "Test narrative about Bhutan"],
["IND", "India", "Test narrative about India"]
]
)
// Trying with vanilla JS
const items = document.getElementById('countrySelector')
let clickedItem = ''
items.addEventListener('change', function (item) {
console.log('You selected: ', this.value);
displayNarrative(this.value)
});
function displayNarrative(countryKey) {
document.getElementById("narrative").innerHTML =
countryData.filter(function (countryRef) {
return countryRef == countryKey;
})
}
// Trying with Jquery
$(document).ready(function () {
var narrative = $('.narrative');
$('select#countrySelector').change(function () {
narrative.columns(2).search($(this).val()).draw();
});
})
</script>