Double the fun: JavaScript array appears twice!

I am currently working on displaying the selected filters from checkboxes. Initially, I create an array containing the values selected from the checkboxes and then aim to add them to a string.

Suppose I have two checkboxes labeled: label1 and label2, my array looks like this: ['label1','label2'].

The expected outcome should be "Filtered by: Label1, Label2" but instead, I end up with

Filtered by: Label1,Label2, Label1,Label2

I believe the issue lies within the for loop where I construct the string, as the array appears correct

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);

If you'd like to see the problem in action, check out this pen: https://codepen.io/anon/pen/pqjYxL

Answer №1

In order to retrieve specific elements, you should utilize the index.

When you don't use an index, you end up assigning the entire array.

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

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

Answer №2

Make sure to access a specific element by its index.

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

An alternative, more concise approach is to utilize the join method.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switching the vertical alignment of grid items in Material UI when the page is collapsed

When the page is collapsed, the Left grid item element moves to the top of the page and the Right grid element is positioned below it. I would like to reverse this behavior so that the Right element appears on top and the Left element below when the page ...

The PHP code embedded within the HTML document and triggered by an AJAX request failed to

Here is an example of my ajax call: function insertModal(link) { $.ajax({ url: link, cache: false, dataType: "text", success: function(data) { $("#modalInput").html(data); }, error: function (request, status, error) { ...

Tips for utilizing multiple components in Angular 2

I am a beginner in angular2 and I am attempting to utilize two components on a single page, but I keep encountering a 404 error. Here are my two .ts files: app.ts import {Component, View, bootstrap} from 'angular2/angular2'; import {events} f ...

Using AngularJS, deleting items by their $index with ng-repeat

I'm currently working with two directives: a query builder and a query row. The query builder directive utilizes ng repeat to display query rows from an array. While the add button functions properly, I am looking to add a delete button as well. Howev ...

Is it possible to utilize setTimeout to demonstrate the execution of a while loop visually?

I am working on a function that generates random numbers between 1 and 6 until it matches a target value of 3. I want to create a visual effect where each randomly generated number is displayed on the page, but I'm facing some challenges with delays. ...

Incorporating promises with ajax to enhance functionality in change events

Consider the scenario where you trigger an ajax request upon a change event in the following manner: MyClass.prototype.bindChangeEvent = function(){ $(document).on('change', '#elementid', function(){ var $element = $(this); $ ...

Vue.JS - Dynamically Displaying Property Values Based on Other Property and Concatenating with

I have a reusable component in Vue.js called DonutChart. <donut-chart :chartName="graphPrefix + 'PerformanceDay'" /> The value of the property graphPrefix is currently set to site1. It is used as part of the identifier for the div id ...

The successful execution of $.ajax does not occur

Starting out with ajax, I wanted to create a simple add operation. Here is the code that I came up with: HTML: <!doctype html> <html> <head> <title>Add two numbers</title> <meta content="text/html;charset=utf-8" h ...

What will occur if I invoke response.end in Node.js while asynchronous I/O operations and callbacks are still executing?

When working with Node.js, what happens if you call "response.end()" while I/O calls and/or callbacks are still being executed? Take a look at the code snippet below: var app = http.createServer(function(request, response) { response.writeHead(200, { ...

Angular.js page failing to reflect changes following Firebase request completion

myApp.controller('RegistrationController', ['$scope', function($scope) { var auth = firebase.database().ref(); // console.log("auth::"+auth); $scope.login = function() { $scope.message = "Welcome " + $scope.user.ema ...

The click event is triggering before it is able to be removed by the code preceding the trigger

Here's a scenario I recently experienced that involves some code written using JQuery. It's more of a statement than a question, but I'm curious if others have encountered this as well: <input type="submit" value="Delete" o ...

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...

Retrieve JSON Object using a string identifier

I created a script that takes the ID of a link as the name of a JSON dataset. $('.link').click(function() { var dataset = $(this).attr("id"); for (var i = 0; i < chart.series.length; i++) { chart.series[i].setData(lata.dataset ...

What is stopping me from utilizing ES6 template literals with the .css() method in my code?

I am currently working on a project where I need to dynamically create grid blocks and change the color of each block. I have been using jQuery and ES6 for this task, but I am facing an issue with dynamically changing the colors. Below is the snippet of m ...

Avoid retrieving data during the fetching process

I have been working on an application that utilizes Redux for state management. Furthermore, I have been using the native fetch method to fetch data. return fetch("https://dog.ceo/api/breeds/image/random").then(res => res.json()); Within my React co ...

A new sub-schema has been created in the JSON schema specifically tailored to a certain property

I needed to create a JSON schema with 3 fields: num, key1, and key2. The fields num and key1 are required, while the field key2 is only mandatory if key1 has a value of 'abc'. Below is the schema structure I came up with: schema = { type: &ap ...

Access the Express server by connecting to its IP address

Is it feasible to connect to an express server using the server's UP address? If so, how would one go about doing this? (Examples of code snippets would be greatly appreciated) ...

JavaScript, AJAX rapid iteration

I am working with some ajax code: $(document).ready( function() { $("#button1").click( function() { $.ajax({ type: "POST", url: "update.php", }); }); }); In my HTML code, I have 200 buttons. How can I ...

The Vue router-view is mistakenly loading the parent component instead of displaying its own content

Here is a simple route configuration: { path: '/', component: Home, }, This route configuration sets the path to the home page and loads the Home component when the path is '/'. However, I am encountering an issue where the Po ...

What is the best way to create a responsive div containing multiple images?

I am working on a slider and my approach is to create a div and insert 4 images inside it. The images will be stacked one above the other using position: absolute, with a width of 1013px, max-width of 100%, and height set to auto for responsiveness. The is ...