Automatically populate the options of a dropdown menu using jQuery

I am a beginner in the world of Javascript, JSON, and jQuery. I am seeking some guidance as I navigate through this new territory. On my JSP page, there is a drop down list that needs to be populated with content when the page loads. To achieve this, I have written a Servlet that retrieves the content for the drop down list in the form of a Map, converts it to a JSON string, and sends it back to the JSP using

response.getWriter().write(json);
. However, I am encountering difficulties in retrieving the result on the JSP side and populating the drop down list accordingly. Below are snippets of my code:

customer.jsp

$(document).ready(function() {
  getCustomerOption('customer'); //attempting to pre-populate the customer drop down list
});

function getCustomerOption(ddId) {
  var dd = $('#' + ddId);
  $.getJSON("http://localhost:8080/WebApps/DDListJASON", function(opts) {
      $('>option', dd).remove(); // Removing previous options in the drop down list
      if (opts) {
        $.each(opts, function(key, value) {
          dd.append($('<option/>').val(key).text(value));
        });
      }
  });
}

down where the drop down list is generated

<select id="customer" name="customer">  
    <option></option>  
</select>

Despite my efforts, the list remains empty after the data retrieval process. It's quite frustrating.

Answer β„–1

It appears that the incorrect function is being called within the document ready function.

Wouldn't it make more sense to use

getInitialOption('customer');

instead of

getCustomerOption('customer');

Answer β„–2

If you want to add more <option> choices to a <select>, you can do so using the following code:

$("#selectID").append("<option>" + text + "</option>");

For more information, check out the JQuery Docs

Answer β„–3

Confusion sets in when trying to grasp the concept of $(''). However, it’s difficult to determine if that is the root issue.

An alternate approach for efficiency would be to generate a list of options in memory and then use one single append with .html(options) instead of adding them individually. This method might facilitate comprehension as well, by constructing the html incrementally before appending it all at once.

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

Error message stating: "jsp encountered a java.lang.NullPointerException"

Hey everyone, I'm new to Java and JSP and I don't have much knowledge about JSON. However, I need to pull data from a database and display it on a JSP page using Bootstrap Data Table. I chose this because it offers features like Pagination, Filte ...

Does this method of long polling have credibility?

Can this Php script be considered a suitable method for long polling, or does it place too much strain on the server? $isNewContent = false; $tokensList = array(); while(!$isNewContent) { usleep(300000); clearstatcache(); $SQLQuery = "SELECT ...

Unable to locate the value of the query string

I need help finding the query string value for the URL www.example.com/product?id=23 This is the code I am using: let myApp = angular.module('myApp', []); myApp.controller('test', ['$scope', '$location', '$ ...

Mapping through multiple items in a loop using Javascript

Typescript also functions Consider an array structured like this const elementList = ['one', 'two', 'three', 'four', 'five'] Now, suppose I want to generate components that appear as follows <div&g ...

What is the method for splitting rows in an r data.frame that includes JSON data?

I am working with a large data frame that contains over 1500 pieces of scraped patent data in JSON format: df <- data.frame(patent = "EP1036268B1", citation = '[{"patent_number": "DE2836002C2", "prior ...

Circe is unable to detect a field if it includes an array

There are 2 different scenarios I'm dealing with: one where I can successfully decode a single user, and another where decoding a list of users fails: import User._ import io.circe._ import io.circe.syntax._ import io.circe.parser.decode class UserSu ...

Issue with html2canvas image download in Firefox

I am currently using HTML2Canvas to try and download a div as an image. It works perfectly fine on Google Chrome, but I am experiencing issues with Firefox. Below is the code snippet: <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0. ...

Attempting to steer clear of utilizing $watch

In the following code snippet, a DOM element is modified if its width is less than 700px. I'm curious, is there an alternative way to achieve the same result without utilizing a watcher? const checkCalendarWidth = () => { if ($('#calenda ...

Sending Parsed Information to Callback for Flexible Use

Is there a way to pass the value of coins, or even better, currency to my callback function so I can freely use the parsed JSON data in other functions? function fetchJSON(path, callback) { var jsonReq = new XMLHttpRequest(); jsonReq.onreadystatechang ...

Encountering a Gson and Hibernate error when attempting to retrieve a Lazy attribute

Presented here is my implementation of a User class: public class User implements Serializable { @Id @Column(name = "USER_ID") @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "USER_LOG") private String log; @Column( ...

How can you capture the VIRTUAL keyCode from a form input?

// Binding the keydown event to all input fields of type text within a form. $("form input[type=text]").keydown(function (e) { // Reference to keyCodes... var key = e.which || e.keyCode; // Only allowing numbers, backspace, and tab if((key >= 48 && ke ...

Tips on stopping the page from scrolling following an ajax request (return false not effective or potentially misplaced)

I am working on a project that involves displaying a tree with information from the Catalogue of Life, including details such as Kingdom, phylum, order, and more. My approach includes using ajax/php to interact with a mySQL database and javascript to handl ...

Is it possible to monitor and keep a record of every modification made to an HTML element?

Can anyone suggest an effective method to monitor changes made to an HTML element? I attempted to utilize JavaScript with jQuery but was unsuccessful. $('div.formSubmitButton input[type="submit"]').change(function(event){ alert( ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

Calling a Coldfusion function from JavaScript/jQuery using a remote server connection

Although I am well-versed in JavaScript/jQuery, I am a newcomer to ColdFusion. After extensive research, I still can't figure out what seems like it should be a simple problem. My goal is to trigger a server-side call to a ColdFusion function from wi ...

Tips for maintaining position when refreshing a web page within a scrolling table

Recently, I came across a helpful tutorial on how to create a table with a fixed header and scrollable body. You can find it here. While the tutorial worked perfectly for me, I encountered an issue when trying to refresh the webpage and maintain my positio ...

Update the text content in the specific span element when the class attribute matches the selected option in the

How can I dynamically update text inside a span based on matching classes and attributes without hardcoding them all? An ideal solution would involve a JavaScript function that searches for matches between span classes and select field options, updating t ...

Responding with a JSON payload in a Laravel application triggers the error "Property of Null cannot be read"

After sending an email and receiving a response in my mobile application from my PHP file (Laravel). $msg ="email sent "; $erreur=false; return response()->json(['Message' => $msg, 'erreur' => $erreur]); However, when ...

Looking for a rival on socket.io

Currently, I am working on a script utilizing socket.io with express in node.js to find an opponent. In this setup, only two players are allowed in a room. If no free rooms are available, a new one should be created automatically. The core logic of the c ...

The volume control does not work on Howler.js for iOS devices

In my Meteor React App, I have made some modifications to the React Howler plugin in order to play two audio tracks simultaneously. I have also added a crossfader feature to adjust the volume of both tracks at the same time. This functionality works perfec ...