I'm trying to find the most efficient way of looping through an array of strings, and then click a corresponding checkbox input that matches any of the values found within the array.
I came up with the below, which works, but I think there's probably a more efficient solution. Anyone have any tips to help me clean this up?
<script>
var comodArr = ['Gold','Copper'];
jQuery(document).ready(function() {
jQuery("#setfilters").click(function() {
<!-- Commodities -->
if(jQuery.inArray("Gold", comodArr) !== -1) {
jQuery('li[val="Gold"] input').click();
}
if(jQuery.inArray("Silver", comodArr) !== -1) {
jQuery('li[val="Silver"] input').click();
}
if(jQuery.inArray("Copper", comodArr) !== -1) {
jQuery('li[val="Copper"] input').click();
}
});
});
</script>
<a class="btn btn-primary" href="#" id="setfilters" style="display: inline-block;"><i class="fas fa-arrow-down"> </i> Set Filters</a>
Updated code after answer below. Much better!
<script>
var fieldVals = ['Gold', 'Copper'];
var fieldValArr = fieldVals.split(', ');
jQuery(document).ready(function() {
jQuery("#setfilters").click(function() {
fieldValArr.forEach(fieldVal => jQuery("li[val='" + fieldVal + "'] input").click());
});
});
</script>