0

I'm trying to create a const or a var for each array item using jQuery, below is my HTML

<div class="taxonomy-list">
<input type="hidden" id="filters-category">
    <ul class="category-list ">
        <li><a href="javascript:;" class="filter-link portfolio-cat-item cat-list_item active" data-slug="" data-id=""
                data-taxtype="">All </a></li>
        <li>
            <a href="javascript:;" class="filter-link cat-list_item" data-slug="uncategorized" data-taxtype="category"
                data-id="1">
                Category </a>
            <span class="remove"><i class="fas fa-times"></i></span>
        </li>
    </ul>



    <input type="hidden" id="filters-post_tag">
    <ul class="post_tag-list ">
        <li><a href="javascript:;" class="filter-link portfolio-cat-item cat-list_item active" data-slug="" data-id=""
                data-taxtype="">All </a></li>
        <li>
            <a href="javascript:;" class="filter-link cat-list_item" data-slug="tag-1" data-taxtype="post_tag"
                data-id="3">
                Tag 1 </a>
            <span class="remove"><i class="fas fa-times"></i></span>
        </li>
    </ul>


</div>

and below is the js I'm trying to use

$('.taxonomy-list input').each(function(index, value) {

const tax_name = [jQuery('.taxonomy-list input')]
for (let i = 0; i < tax_name.length; i++) {
console.log(`tax-${index}: ${this.id}`);
}
});

What I'm willing to get is in below format

const tax_0 = jQuery('#filters-category').val().split(',');
const tax_1 = jQuery('#filters-post_tag').val().split(',');

there will be more tax-i coming up, so I need to create a new const for each of them

  • 2
    You can't create `const` variables dynamically (unless you use something like `eval` which isn't recommended) (see ["Variable" variables in JavaScript](https://stackoverflow.com/q/5187530)), instead, create an array, and use indexes `const tax = $('.taxonomy-list input').map(function() {return this.id;}).get();`, then use `tax[0]`, `tax[1]` to access your ids – Nick Parsons Dec 14 '21 at 10:59
  • Also, VERY BAD idea to name your variables or constants with a minus, this will not work. Use underscore. – Shrimp Dec 14 '21 at 11:01
  • I'm not sure why you opted to go with a new `const` or `let`, as this indeed would require some meta-programming with `eval` which is very error and bug prone way. In most cases I would go with an object and I would add dynamic keys to it, named as you wish. – Jared Dec 14 '21 at 11:13
  • hey @NickParsons I'm quite newbie to jquery world, so I had no idea where to proceed with, I would be really thankful, if you could help me with the code to get me in the right direction, thanks a lot for your help :) – Luice Phillips Dec 14 '21 at 11:31

0 Answers0