Skip to content
Fix Code Error

What is the best way to add options to a select from a JavaScript object with jQuery?

March 13, 2021 by Code Error
Posted By: Darryl Hein

What is the best method for adding options to a <select> from a JavaScript object using jQuery?

I’m looking for something that I don’t need a plugin to do, but I would also be interested in the plugins that are out there.

This is what I did:

selectValues = { "1": "test 1", "2": "test 2" };

for (key in selectValues) {
  if (typeof (selectValues[key] == 'string') {
    $('#mySelect').append('<option value="' + key + '">' + selectValues[key] + '</option>');
  }
}

A clean/simple solution:

This is a cleaned up and simplified version of matdumsa’s:

$.each(selectValues, function(key, value) {
     $('#mySelect')
          .append($('<option>', { value : key })
          .text(value));
});

Changes from matdumsa’s: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().

Solution

The same as other answers, in a jQuery fashion:

$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
                    .attr("value", key)
                    .text(value)); 
});
Answered By: matdumsa

Related Articles

  • Form field border-radius is not working only on the…
  • Trouble with boxes appearing/hiding based on selection
  • Specifying java version in maven - differences…
  • Plugin…
  • How to use html template with vue.js
  • I'm working on pagination for my project. How do I…
  • Could not calculate build plan: Plugin…
  • Generating a drop down list of timezones with PHP
  • Failed to execute goal…
  • Bootstrap-vue: how can I display the text of a…
  • How do you remove all the options of a select box…
  • Maven: The packaging for this project did not assign…
  • Building executable jar with maven?
  • Include resource directory into Quarkus target output
  • Can't install via pip because of egg_info error
  • m2eclipse error
  • Problems using Maven and SSL behind proxy
  • Spring Boot - Cannot determine embedded database…
  • What does backbone.js do with models that are not…
  • Nuxt Hot reloading for new components Is not working
  • Why am I getting a "401 Unauthorized" error in Maven?
  • TypeScript metadata reflection references other…
  • Unable to Click on Dropdown using Python Selenium
  • How to track untracked content?
  • How to remove a newline from a string in Bash
  • java.lang.ClassNotFoundException:…
  • Adding Google Translate to a web site
  • Tomcat 7 "SEVERE: A child container failed during start"
  • Vue Component Library - Can't import from dist
  • Aurelia UX showcase app fails to load
  • Aurelia bundling issue with virtual directory
  • Unable to Build using MAVEN with ERROR - Failed to…
  • How to find Control in TemplateField of GridView?
  • Maven is not working in Java 8 when Javadoc tags are…
  • Svelte application not working on android version…
  • ./components/Avatar.tsx Error: Cannot find module…
  • Spring data jpa- No bean named…
  • Maven2: Missing artifact but jars are in place
  • The superclass "javax.servlet.http.HttpServlet" was…
  • How to use java.net.URLConnection to fire and handle…
  • Jetpack Compose and Hilt Conflict
  • How do I check if a type is a subtype OR the type of…
  • How to use Servlets and Ajax?
  • "The import org.springframework cannot be resolved."
  • Worker Script Failing to Load for Vue Webpack Built App
  • Is it possible to apply CSS to half of a character?
  • jQuery .each() index?
  • Unable to compile simple Java 10 / Java 11 project…
  • Smart way to truncate long strings
  • hide select options using only css
  • Maven does not find JUnit tests to run
  • Exception in thread "main"…
  • How do I add options to a DropDownList using jQuery?
  • Maven Could not resolve dependencies, artifacts…
  • Best practise: How to implement plugins for spring…
  • UnsatisfiedDependencyException: Error creating bean…
  • Exception in thread "JobGenerator"…
  • Rollup CommonJS plugin throwing error when importing…
  • Svelte for IE11 with Babel transpiler on Snowpack
  • convert a html table with select to Json
  • How do I tell Maven to use the latest version of a…
  • Proper use of the IDisposable interface
  • "Non-resolvable parent POM: Could not transfer…
  • Managing jQuery plugin dependency in webpack
  • How to show multiple select options when user select…
  • What is the difference between typeof and instanceof…
  • Remove border radius from Select tag in bootstrap 3
  • Webpack: Unable to find module with ID: main --…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Typescript Symbol.species typing inference
  • How do you go into production with polymer project?
  • How can I download a specific Maven artifact in one…
  • Error while trying to rename downloaded pdf file in…
  • Is it possible to call a component method in nuxt…
  • How to unescape a Java string literal in Java?
  • Scraping Tables in Python Using Beautiful Soup…
  • In Jquery show selected a value from the searched…
  • How to remove local (untracked) files from the…
  • Various ways to remove local Git changes
  • .bind no longer working after upgrading to new…
  • OnChange event using React JS for drop down
  • How to get Maven project version to the bash command line
  • Latest jQuery version on Google's CDN
  • "Thinking in AngularJS" if I have a jQuery background?
  • Datepicker plugin not working in phonegap 3.0.0
  • What are the undocumented features and limitations…
  • What is the scope of variables in JavaScript?
  • How do I put all required JAR files in a library…
  • jQuery Mobile: document ready vs. page events
  • Reduce vs Collect method on Parallel Streams vs…
  • Is it possible to have html-webpack-plugin generate…
  • Incorporate JQuery-file-upload to application
  • Test resources not added to classpath
  • webpack-dev-server npm run dev throwing TypeError:…
  • Sapper/Svelte rollup/plugin-json giving error with stripejs
  • Webpack build fails for IE (11)
  • How to integrate Material UI into Svelte project
  • Sort table rows In Bootstrap
  • What are the best JVM settings for Eclipse?
  • java.lang.OutOfMemoryError: Java heap space in Maven

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I reformat HTML code using Sublime Text 2?

Next Post:

Cast Double to Integer in Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error