1

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">&nbsp;</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>
4
  • Do you need to be able to undo this if user changes filters? Commented May 19, 2021 at 21:50
  • Not sure if it's needed. What's your thought there? The array is established dynamically on page load. It's meant to be a button that pre-sets filters based on the user's known db stored interests. Commented May 19, 2021 at 22:29
  • 1
    Hard to make suggestions without knowing how the UI needs to work Commented May 19, 2021 at 22:34
  • Well, if it wasn't obvious I'm manipulating a pre-existing UI to achieve a usability outcome that wasn't intended by the developer. I'm detecting values of "my" interests and checking inputs to achieve a quick filtered result. One could still use the current UI to select/de-select as needed. Commented May 19, 2021 at 22:37

1 Answer 1

1

Loop through the array.

comodArr.forEach(comod => jQuery(`li[val="${comod}"] input`).click());

BTW, you shouldn't add nonstandard attributes like val to elements. If you need to add your own attributes, use data-XXX, e.g. data-val="Gold"

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Much appreciated. Not my code I'm manipulating but agreed on nonstandard attrs on elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.