What is the best way to populate dropdown menus using JavaScript?

I'm facing an issue with my ajax request where I am unable to populate the options of a select tag. This problem is occurring in multiple blocks where the select tag serves the purpose of choosing a type of product.

Here is how my select tag looks like:

<select class="form-control" name="type" id="select-types">
</select>

This is the ajax request I am using:

function getTypes() {
 $.ajax({
      url: `/types/json`
  }).done(function(res){
    console.log(res)
    })}

The response "res" has the following structure:

{types: [{"id":1,"name": Name}, ...]}

Imagine having 5 blocks each containing the same select element.

1. How can I only fill the last one?

2. What is the best approach to populating it correctly?

Answer №1

To retrieve the final element, a possible approach is to utilize the getElementsByTagName method. By iterating over each desired option within the select element, you can cycle through the list of types and generate an option for each type. Subsequently, these options can be appended to the last select.

const types = [{"id":1,"name": "Something"}, {"id":2,"name": "New Text"}];
const allSelects = document.getElementsByTagName('select');
const lastSelect = allSelects[allSelects.length - 1];

types.forEach((type) => {
  const option = document.createElement("option");

  option.value = type.id;
  option.text = type.name;
  
  lastSelect.appendChild(option)
})

Answer №2

  1. To restrict options to 5 items, simply use .slice(0, 5)
  2. Modify the innerHTML of your select element to dynamically generate options

const fakeRequest = () => new Promise(resolve => {
  setTimeout(() => {
    resolve([
      'opt1', 'opt2', 'opt3', 'opt4', 'opt5', 'opt6', 'opt7'
    ])
  }, 1000)
})

const select = document.getElementById('select-types')

fakeRequest().then(options => {
  const showingOptions = options.slice(0, 5)
  select.innerHTML = showingOptions.map(value => `<option value='${value}'>${value}</option>`)
})
<select class="form-control" name="type" id="select-types">
</select>

Answer №3

This method is effective. It involves mapping the type list to option HTML syntax and then combining them into a single string. Finally, this string is set as the innerHTML of the select element.

function fetchTypeOptions() {
 $.ajax({
      url: `/types/json`
  }).done(function(response) {
       let selectElement = document.getElementById('select-types');    
       let options = 
          response.types.map(type => `<option value=${type.id}>${type.name}</option>`)
                   .join('\n');
       selectElement.innerHTML = options;
  });
}

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

Troubleshooting Test Failures: The importance of passing $controller in the callback of 'it' function in Angular

As a newcomer to testing, I am attempting to write Jasmine/Karma tests for a controller. Given a sample test to use as a starting point, the issue arises when passing the $controller in the argument of the it block. The test passes successfully with this s ...

What is the reason for webpack searching for jQuery even though it is not necessary for the module?

Before I proceed with my question, I want to clarify that I may not fully grasp the intricacies of this issue and I apologize if it does not meet the standards of Stackoverflow's Q&A. Currently, we are facing a challenge in our project while tryi ...

Ways to shift text upwards while scrolling in a downward direction?

I'm a beginner with jQuery and I could use some assistance. My goal is to have the text move upwards and a static box slowly disappear as you scroll down the website. Something similar to what you see here: p, body { margin: 0; padding: 0; } b ...

Can existing servers support server side rendering?

I am currently working on building a Single Page Application (SPA) using the latest Angular framework. The SPA will involve a combination of static HTML pages, server side rendering, and possibly Nunjucks templating engine. My dilemma lies in the fact th ...

Incorporating Vuetify into a Vue CLI application with the help of webpack

I am facing an issue with my Vue CLI application that uses Webpack and Vuetify. The Vuetify components are not loading properly, and I keep getting the following warnings: Unknown custom element: < v-app > - did you register the component correctly? ...

What could be the reason behind jQuery replacing the entire span with .text?

I am dealing with the following HTML code snippet: <p><input id="revenue" type="text" value="100000" /><span id="howmuch"><a href="" class="ka_button small_button small_cherry" target="_self" style="opacity: 1; "><span>How Mu ...

Tips for transferring information to an input field's value

There's an input box with an empty value that needs to be filled with data. <input type="text" value="" class="box"> $('.skills-tags').on('click', function(){ var value = $(".skills-tags").val(); $('.label-pr ...

Express/NodeJS encountering a CORS problem, causing services to be inaccessible in Internet Explorer

Currently, I am working on a REST-based service implemented in Express/NodeJS. The code includes CORS (Cross Origin Resource Sharing) implementation to allow services to be consumed from browsers like Chrome and Firefox. However, there seems to be an issue ...

Implement a JavaScript confirm dialog for a mailto hyperlink

Is there a way in javascript to automatically detect mailto links on the page and prompt a confirmation dialog when clicked by a user? I came across a method on this website for displaying an alert message. My knowledge of javascript is very basic. It&ap ...

"Enhance Your Text Fields with Angular2 Text Masks for Added Text Formatting

Is there a way to combine text and numbers in my mask? This is what I am currently using: [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] The above code only allows for numbers. How can I modify it to allow f ...

What is the best way to incorporate a JavaScript file into my ejs file using node.js?

As I work on creating a website for my school project, I encountered a challenge involving including CSS files in node.js. Thankfully, after researching on stackoverflow, I was able to find a solution. Now, I am facing another issue - how to include a java ...

NuxtLink sending users to incorrect destination URL

I am facing an issue with my static generated Nuxt site. Everything works perfectly fine when I host it locally, but once I load it on GitHub Pages, the NuxtLink elements' hrefs are incorrect. For instance, one of my links looks like this: <NuxtLi ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

Is there a way to personalize the chart tooltip in jqplot to fit my preferences?

I have a chart that displays data. I would like the x-axis labels to show in the format MM/DD, and in the tooltip, I want to display data in the format HH:y-axis. For example, in the chart below, I want the x-axis labels to be 'Oct 15','Oct ...

Can you elaborate on the contrast between React Server Components (RSC) and Server Side Rendering (SSR)?

I'm curious about the differences between RSC in React 18 and SSR in NextJS. Can anyone explain? ...

Customizing the Material UI theme colors using Typescript

I have created my own unique theme and now I am attempting to assign one of the custom colors I defined to a button. However, when I try to set it as: color={theme.pallete.lightGrey} I run into this error message: No overload matches this call Overload 1 ...

JavaScript (Automatic) for a full-screen webpage display

I'm having trouble creating a webpage and setting it to fullscreen mode. Here's the JavaScript code I have: var elem = document.getElementById("fulscreen"); var fs = document.getElementById("body"); elem.onclick = function() { req = fs.webk ...

Unable to use .ajax within autocomplete function

I've been struggling for days to make the jQuery autocomplete feature work. Currently, I am able to type in the textbox and see exactly what I want, but the issue arises when I click on the desired option - it does not show up in the textbox. I suspec ...

A step-by-step guide on deleting an element within a div using jQuery

I am attempting to delete an HTML element using JQuery like this $('#' + divId + ' .settings_class').remove('.print_settings'); This code does not result in an error or remove the specified html element, however, the selecto ...

What methods can I use to make sure the right side of my React form is properly aligned for a polished appearance?

Trying to create a React component with multiple input field tables, the challenge is aligning the right side of the table correctly. The issue lies in inconsistent alignment of content within the cells leading to disruption in overall layout. Experimente ...