I'm setting up a filter for my project that will filter specific values based on whatever name is selected, or selecting all values is a user selects 'all'. I have the button ID and the input class name stored in an object and then use Object.keys and forEach to iterate through them. Whenever a user selects a specific option, I want to hide all other options so only the value of the selected option appear. What I have now works fine but I want to try to condense it to a DRY format so the code looks cleaner. Any ideas on how to condense the .hide() methods is greatly appreciated! Thanks!
let filterObjs = {
'#allBtn': '.all',
'#name1Btn': '.name1',
'#name2Btn': '.name2',
'#name3Btn': '.name3',
'#name4Btn': '.name4',
'#name5Btn': '.name5'
}
Object.keys(filterObjs).forEach(function (key) {
let value = filterObjs[key];
$(key).on("click", function () {
if ($(value).val() === "All") {
$(value).removeAttr("style");
$('#filterOption').html($(value).val())
$('.name1').hide()
$('.name2').hide()
$('.name3').hide()
$('.name4').hide()
$('.name5').hide()
} else if ($(value).val() === "Name1") {
$(value).removeAttr("style");
$('#filterOption').html($(value).val())
$('.all').hide()
$('.name2').hide()
$('.name3').hide()
$('.name4').hide()
$('.name5').hide()
} else if ($(value).val() === "Name2") {
$(value).removeAttr("style")
$('#filterOption').html($(value).val())
$('.all').hide()
$('.name1').hide()
$('.name3').hide()
$('.name4').hide()
$('.name5').hide()
} else if ($(value).val() === "Name3") {
$(value).removeAttr("style")
$('#filterOption').html($(value).val())
$('.all').hide()
$('.name1').hide()
$('.name2').hide()
$('.name4').hide()
$('.name5').hide()
} else if ($(value).val() === "Name4") {
$(value).removeAttr("style")
$('#filterOption').html($(value).val())
$('.all').hide()
$('.name1').hide()
$('.name2').hide()
$('.name3').hide()
$('.name5').hide()
} else if ($(value).val() === "Name5") {
$(value).removeAttr("style")
$('#filterOption').html($(value).val())
$('.all').hide()
$('.name1').hide()
$('.name2').hide()
$('.name3').hide()
$('.name4').hide()
}
});
});