Dealing with duplicate entries in a dropdown menu when receiving a JavaScript AJAX response

I am attempting to display multiple selected values in a dropdown list that are coming from a database. The contents of my dropdown list are dependent on another dropdown list.

Here is the JS code I am using:

var cityName = <?= json_encode($cityName); ?>;
var area_name = document.getElementById('area_name').value;
$.ajax({
  'url': '<?= base_url('utility/cityByArea'); ?>',
  'type': 'POST',
  'dataType': 'JSON',
  'data': {
    area_name : area_name
  },
  success: function(response) {
    $('#city_name').find('option').not(':first').remove();
    $.each(response, function(index, data) {
      for(var i = 0; i < cityName.length; i++) {
        $('#city_name').append('<option value="' +data['city_id_primary']+ '" ' +(cityName[i] == data['city_id_primary'] ? 'selected' : '')+ '>' +data['city_name']+ '</option>');
      }
    });
  }
});

Although I am able to get the correct selected values in the dropdown list, the values are being repeated.

To retrieve the database value, I am using PHP CodeIgniter code

var cityName = <?= json_encode($cityName); ?>;
which stores the values in an array.

https://i.sstatic.net/f6UfL.png

Displayed above is the output of console.log(cityName);.

https://i.sstatic.net/eeoGX.png

I am successfully displaying the output in the dropdown list.

However, I need assistance in showing single values only.

I would appreciate any kind of help. Thank you in advance.

Answer №1

Your current code is causing each city to be outputted cityName.length times because you are appending the operation inside both loops.

If you want to select multiple options based on the cities in the cityName list, separate the matching logic from the option appending logic.

The approach is straightforward:

success: function(response) {
    $('#city_name').find('option').not(':first').remove();

    // loop through each possible option
    $.each(response, function(index, data) {
      var selected = false; // boolean variable to check if the option value matches any existing city

      // loop through existing cities
      for(var i = 0; i < cityName.length; i++) {
        if (cityName[i] == data['city_id_primary']) {
          selected = true; // we found a match
          break; // exit the loop since a match was found
        }
      }

      // append the option to the dropdown only once and set its selected attribute based on the "selected" boolean.
      $('#city_name').append('<option value="' +data['city_id_primary']+ '" ' +(selected === true ? 'selected' : '')+ '>' +data['city_name']+ '</option>');
    });
  }

P.S. There may be a more concise way to write this using jQuery array functions, but this version is easier to comprehend.

Answer №2

Revise the logic for two functions:

for (var i = 0; i < cityName.length; i++) {
    $.each(response, function (index, data) {
        $('#city_name').append('<option value="' + data['city_id_primary'] + '" ' + (cityName[i] == data['city_id_primary'] ? ' selected ' : '') + '>' + data['city_name'] + '</option>');
    });
}

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

Choose an element that has been generated dynamically using jQuery

Here is an example HTML table to work with: <table id="#myTable"> <tr id="#row123"><td>Content</td></tr> </table> To insert a new row using jQuery, you can use the following code: $('#myTable').prepend(&ap ...

Enhancing Donut Chart with d3.js

After working for several hours, I'm having trouble getting my d3.js donut graph to update with new data. Here's my HTML: <body> <div id="pie"></div> <script src="pie.js"></script> </body> And he ...

Using JavaScript and jQuery to make calls to the Web API

I am struggling with Java-script callback due to lack of experience. Can anyone provide assistance in resolving the issues I am facing with the code? My goal is to perform a callback from a .json file and search it by ID. While I can display all customers, ...

Tips for enhancing the width of the extrude shape in the x and z axes using Three.js

After creating a shape using extrude geometry, I found that I needed to increase the thickness along the x and z axes. Although I used bevelThickness to increase the thickness along the y axis, I still need to adjust it further. For reference, please see ...

Transferring information among various instances of a single controller (ng-controller)

I am relatively new to using Angular and I am facing a challenge with a seemingly simple task that is proving to be more complex within the framework. The issue at hand involves data manipulation, specifically with a variable named var1. I am modifying th ...

Is there a way to customize the appearance of an unordered list by setting it to display as an image instead of default bullets? I want to

I have been attempting to achieve this desired outcome. However, my efforts to reproduce it resulted in the check marks being rendered at a smaller size than intended due to using an SVG file. An example of this issue can be seen in the following image: I ...

regenerate access credentials using extjs

Utilizing extjs Ext.Ajax.request for making REST API calls in my application. Implementation of oauth authentication is used with the REST APIs. I am seeking a way to automatically refresh the token if it expires during an ext.ajax.request call, allowing ...

What is the reason for NextJS/React showing the message "You probably didn't export your component from the file where it was declared"?

What's the Issue The error code I am encountering Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the ...

What is the proper way to implement parameters and dependency injection within a service?

My objective is to achieve the following: (function(){angular.module('app').factory("loadDataForStep",ls); ls.$inject = ['$scope','stepIndex'] function ls ($scope, stepIndex) { if ($routeParams ...

Angular 8's array verification feature lacks the ability to recognize preexisting elements

I've been trying to add and delete items in an array when a user selects or deselects the same item. However, it appears that either my array is not working properly or there is a bug in my code causing it to fail. <div class="grp-input"> ...

The hyperlink in the mobile version of the mega menu is unresponsive in HTML

I am encountering an issue with the navigation menu on my Laravel website. The menu links work correctly on the desktop version, but none of the anchor tag links are functioning properly on the mobile version. HTML <div class="menu-container"> < ...

Displaying JSON data in an HTML table cell format

Hey everyone, I need some help with the following task: I am working on displaying a list of log lines in an HTML table. Some of these lines will contain JSON strings, and I want to format the JSON data within the table when the HTML file is loaded from ...

Learn how to efficiently disable or enable a button in Angular depending on the selected radio button

In order to disable the button when the remarks are marked as failed. Here is an example scenario: Imagine there is an array containing two to four items. First example: ITEM 1 -> FAILED -> Remarks (required) ITEM 2 -> FAILED -> Remarks (r ...

Why is my event.target.value not updating correctly in React useState?

My problem is that when I use useState, I am receiving incorrect numbers For example, if I print e.target.value it might display 1, but my selectedIndex shows 2. Similarly, when I have a selectedIndex of 0, it retrieves something different like 1. Any tho ...

Is your Angular2 form page experiencing reloading issues?

I am currently incorporating Angular2 into my project. I am facing an issue where the page keeps refreshing, and I'm unable to determine the cause. Below is a snippet of my form: <form> <div class="form-group"> ...

Switch up the like button for users who have previously liked a post

Greetings, I trust everything is going well. I am attempting to implement a feature where users can like a post or article created by others using a button. I have established a const function named "getAPostLikeRecord()," which retrieves a list of users w ...

There are no headers present in the response from apollo-client

I am currently utilizing a graphql api along with a vue.js frontend that incorporates the apollo client for fetching data from the backend. This setup has been operating smoothly thus far. In each response header, the server sends back a new JWT-Token whi ...

produce in the element that is invoked within an each function

This snippet is a key part of my component's template: {{#each displayResults}} <li {{action addSelection this}} {{bindAttr class=\":result active\"}}> {{#if controller.template}} {{yield}} {{else}} <span class=\ ...

retrieve the most recent file following a $group operation

I am currently utilizing the official MongoDB driver specifically designed for Node.js. This is how my message data is organized. Each post consists of a timestamp, a user ID, and a topic ID. [ { "_id" : ObjectId("5b0abb48b20c1b4b92365145"), "t ...

AJAX call not being executed by the script

I have been trying to send an ajax request to a specific file, but for some reason the file does not complete the operation. I can confirm that the request reaches the file because it echoes 'request received' and then stops abruptly. I am puzzle ...