JavaScript - Populating Dropdown Menu with Fresh Information

I'm attempting to populate a combobox (input) with data fetched via AJAX. The goal is to display every city associated with a selected state, chosen from another select control (the state control).

My Attempt:

I've implemented the "change" event on the state comboBox, so that when a state is selected, I search for its cities and populate the city control.

$("#state").on("change", function () {

    getCities($(this), $("#city"));
});

It's currently functioning as expected, but my main issue is that after bringing in the data to the control, I need to click on it to refresh it (the previous state data remains). Ideally, this should happen automatically once I finish selecting the state from the state select input. Another problem I'm encountering is that the first option "--- SELECT CITY ---" gets selected every time the state select input changes its cities. Below is the function code for reference:

function getCities(stateControl, cityControl) {

    if (stateControl.val()) {
        var options = '<option value="0" selected="selected">--- CHOOSE CITY --- </option>';
        cityControl.html(options);
        var dataString = "state="+stateControl.val();
        $.ajax({
            type: "POST",
            url: "cities.php",
            data: dataString,
            dataType: "json",
            success: function (response) { 

                for(var i=0; i < response.length; i++){    
                    options += '<option value="' + response[i].cod_cidade + '">' + response[i].nome + '</option>';                                                      
                };
                cityControl.html(options);
            }
        });
    }
}

}

Answer №1

Enhance Your UI Experience:

   Remove all options in the dropdown list with jQuery:
$("#city").find('option').remove();

Or, achieve the same result with pure javascript:

Clear all options in the dropdown list using javascript:
document.getElementById('city').options.length = 0;

Simply execute this code before adding new options to ensure a fresh start.

Explore further details here

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

What is the quickest way to increase value in the DOM?

Is there a more efficient method for incrementing a DOM value that you know of? let progress = +document.getElementById("progress").innerHTML; progress++; document.getElementById("progress").innerHTML = progress; Perhaps something like t ...

Is there a way to implement a method on AirDatepicker within my custom JavaScript file?

I am currently working with AirDatepicker v3.3.5 in my app.js file: window.dateRangePicker = new AirDatepicker('.date-range', { range: true, maxDate: new Date(), multipleDatesSeparator: ' - ' }); After referring to the docu ...

Ways to Extract HTML DOM Attributes using Jquery

I am working with an HTML DOM that is saved in a JavaScript Variable. I need to figure out how to retrieve its attributes. For example: <script> //element_html is ajax response var element_html = '<h1 style="" class="app-control " data-order ...

Unusual method of declaring variables in the world of Eloquent JavaScript

I was diving into the Node.js section of the online version of Eloquent JavaScript (by the way, a fantastic book). The examples all used the following pattern to capture the result of a require() call: const {fs} = require("fs"); However, when I attempte ...

What is the solution to preventing contentEditable="true" from inserting <div> instead of <p> when the return key is pressed?

I have a div <div contentEditable="true"> <h1> My headline</h1> </div> When editing the text inside the <h1> tag and pressing return, a new div is added underneath instead of the usual paragraph tag. Resulting in: < ...

Is the "add" feature malfunctioning?

My code is experiencing an issue where the URL and ID are not being passed correctly from one function to another. When I click on a link that contains the add() function, it fails to capture the URL and ID. <a href="#" style="color:#FFF;" onclick="add ...

Tips for making a hide and reveal FAQ section

Currently working on creating a FAQ page for my website, I ran into a challenge. My goal is to have a setup where clicking on a question will reveal the answer while hiding any previously open answers. So far, I have managed to achieve this functionality p ...

Navigating THREE.js Editor: Leveraging the main script within a sample illustration

One of the tools I can utilize is the THREE.js editor found at . Opening an example app like PONG is also possible. Interactive animation can be activated by clicking on Play in the menu bar, and deactivated by clicking on Stop. My goal is to edit the Mai ...

In Next.js, the 404 error page is displayed using getInitialProps

Currently, I am learning how to redirect users in getInitialProps by following a helpful example. Here is the link to the example I am referring to However, I encountered an issue where when I try to return a 404 error using the code snippet provided, in ...

Contact form repair completed - Messages successfully delivered

I am facing an issue with the contact form on my HTML landing page. Currently, when you click the 'Submit' button, it redirects to a new PHP page displaying 'Success'. Is there a way to make it so that upon clicking 'Submit' a ...

Are there any other commands similar to "now dev" available on Vercel?

"now dev" is not being recognized as a command on my Windows 10 system with Vercel, JavaScript, Node.js, and MongoDB. I am trying to test my API using Postman, but when I enter the "now dev" command in the command prompt, it does not wo ...

Angular directive failed to correctly retrieve object

I have a person object loaded from the backend that is structured as follows: { "PersonId":"19894711-2eb9-4edf-92c6-85de2b33d1bb", "Firstname":"Jacky", "Lastname":"Chan", "DateOfBirth":"1963-09-18T00:00:00", "CreateDate":"2015-12-11T09 ...

Sending Ajax data to a controller function

I am looking for guidance on how to pass values from my view to my controller using ajax. As someone who is new to working with ajax, I would appreciate some assistance in understanding the process. Full Page @model ALSummary.Models.MonthReport @{ ...

Difficulty in incorporating reCaptcha into a PHP contact form and submitting it using AJAX

After integrating AJAX into a contact form that already had reCaptcha, I am facing issues with retrieving the g-recaptcha-response. The PHP code for reCaptcha remains unchanged from when it was functioning correctly, and I'm unsure of what modificatio ...

Interactively retrieve data from a nested field in mongoDB

Querying my mongoDb is my current task, but I'm facing a challenge with creating a dynamic query. Each user has a different set of preferences, making it tricky to create a standardized query. dynamicArray = [ 'sample1', 'sample ...

Deliver Compressed Files following Angular CLI --Prod Configuration

After using the Angular CLI's command to minify my basic Angular app, a dist folder was generated with the project folder and minified files. However, when I run ng serve, it always serves the unminified development files, whether it's in the roo ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

What is the top choice for creating a shallow copy of an array

While delving into the vue source code today, I stumbled upon a method of writing that left me puzzled. view source const deduped = [...new Set(pendingPostFlushCbs)] My initial thought is that it is a shallow copy of the array. But why is there a need t ...

Using Axios to facilitate communication between API and Interface

I am facing a challenge in establishing communication between the API and the Interface. To explain further: I send a JSON file from the API, but I am unable to retrieve it and display it in the Interface. The JSON structure is simple: {"name": "joe"} My ...

How to extract information for divs with specific attribute values using Jquery

I have multiple divs with IDs like #result-1, #result-2, each followed by a prefix number. To count the number of list items within these divs, I use the following code: $(document).ready(function () { var colorCount = $('#result-1 .item-result ...