1

I'm trying to show the filters selected from a checkbox. First I'm creating an array of values selected from the checkboxes and I'm trying to append to a string

For example I have two checkboxes labeled: label1 and label2, I built the array ['label1','label2'].

The desired result would be "Filtered by: Label1, Label2" but instead I get Filtered by: Label1,Label2, Label1,Label2

I guess it's something in the for loop where I'm trying to build the string, because the array looks fine

let topLabel = jQuery('.industry-filter').data('selected-text') + ' ';
let termsName= ['Industry', 'Category']
if(termsName.length){
  for(var j = 0; j < termsName.length; j++){
    if(j == termsName.length - 1){
      topLabel += termsName;
    }else{
      topLabel += termsName+', ';
    }
  }
}else{
  topLabel = jQuery('.industry-filter').data('text');
}

$('.industry-filter').text(topLabel);

Here is a pen that shows the issue: https://codepen.io/anon/pen/pqjYxL

2
  • You forgot to access the array element using the index if(j == termsName.length - 1){ topLabel += termsName[j]; }else{ topLabel += termsName[j]+', '; } Commented Dec 13, 2018 at 9:46
  • how about use join instead termsName.join(", ", termsName) you're just making your code complicated Commented Dec 13, 2018 at 9:48

2 Answers 2

1

You need to access by index.

Without using index you're assigning the complete array.

let topLabel = jQuery('.industry-filter').data('selected-text') + ' ';
let termsName= ['Industry', 'Category']
if(termsName.length){
  for(var j = 0; j < termsName.length; j++){
    if(j == termsName.length - 1){
      topLabel += termsName[j];
                           ^^^
    }else{
      topLabel += termsName[j] +', ';
                           ^^^
    }
  }
}else{
  topLabel = jQuery('.industry-filter').data('text');
}

$('.industry-filter').text(topLabel);
Sign up to request clarification or add additional context in comments.

Comments

0

You should access one element by its index.

if(j == termsName.length - 1){
  topLabel += termsName[j];
}else{
  topLabel += termsName[j]+', ';
}

One short version of your solution could be using join method.

if(termsName.length){
   topLabel += termsName.join(',')
}

Comments

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.