DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Call Rest API by Using jQuery AJAX in Spring Boot? [Video]
  • jQuery vs. Angular: Common Differences You Must Know
  • CSS3 Transitions vs. jQuery Animate: Performance
  • Better Scaffolding with jQuery - Part I

Trending

  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Understanding and Mitigating IP Spoofing Attacks
  1. DZone
  2. Coding
  3. Frameworks
  4. Populate a jQuery Dropdown From AJAX

Populate a jQuery Dropdown From AJAX

This quick snippet will show you how to handle the AJAX request for a jQuery drop-down menu and populate it with the response.

By 
Paul Underwood user avatar
Paul Underwood
·
Aug. 05, 15 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
123.6K Views

Join the DZone community and get the full member experience.

Join For Free

In a recent project I had to correct a lot of AJAX requests that will populate a HTML select dropdown, in this post I'm going to show you a quick snippet of how to handle the return of the AJAX request and populate a dropdown with the response.

First we start off by creating a HTML dropdown on the page with an ID attribute.

<select id="dropdown"></select>

Next we create an AJAX POST in jQuery to a urlPath that will return the data we need in a JSON object. On the return of this AJAX request we are going to parse the response and use this in the helpers.buildDropdown function that we will create.

$.ajax({
            type: "POST",
            url: urlPath,
            success: function(data)
            {
                helpers.buildDropdown(
                    jQuery.parseJSON(data),
                    $('#dropdown'),
                    'Select an option'
                );
            }
        });

The response that we are expecting from the AJAX call is a JSON object similar to the data below, it can be made up of multiple rows which each have an ID column and a NAME column.

The ID column is going to be used to populate the option element value attribute while the NAME column is going to be used as the text inside the option element. You can have whatever fields you want for this but in this example these are the columns that are expected in the buildDropdown function.

[
    {"id":1,"name":"Option 1"},
    {"id":2,"name":"Option 2"},
    {"id":3,"name":"Option 3"},
    {"id":4,"name":"Option 4"},
    {"id":5,"name":"Option 5"},
]

With creating the data and returning it in a way that is expected we can now create the buildDropdown function. First we start off by placing this function inside a helpers namespace, therefore you can continue to add to this namespace when you create more helpful functions.

Next create the function and pass in 3 parameters, the result is the JSON data object, the dropdown is the jQuery object of the dropdown, emptyMessage is the text we can use on the first empty option.

var helpers =
{
    buildDropdown: function(result, dropdown, emptyMessage)
    {
        // Remove current options
        dropdown.html('');

        // Add the empty option with the empty message
        dropdown.append('<option value="">' + emptyMessage + '</option>');

        // Check result isnt empty
        if(result != '')
        {
            // Loop through each of the results and append the option to the dropdown
            $.each(result, function(k, v) {
                dropdown.append('<option value="' + v.id + '">' + v.name + '</option>');
            });
        }
    }
}
AJAX JQuery

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Call Rest API by Using jQuery AJAX in Spring Boot? [Video]
  • jQuery vs. Angular: Common Differences You Must Know
  • CSS3 Transitions vs. jQuery Animate: Performance
  • Better Scaffolding with jQuery - Part I

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!