Display a printing choice for every element within an array

I'm currently working with an array and attempting to add a new <option> element for each item in the array.

Here is the approach I have taken:

 array.forEach(function(arr) {
   console.log(array);
   $(".filterSection .department").append('<option value="'+array+'">'+array+'</option>');
 }); 

However, the issue lies in the fact that when the options are generated, all values in the array are displayed within each <option>. Although new option tags are created, they end up containing all items from the array as their value and text.

Check out the complete demo below:

var array = ["Value 1", "Value 2", "Value 3"];

array.forEach(function(arr) {
  console.log(array);
  $(".department").append('<option value="' + array + '">' + array + '</option>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select class="department" name="department" id="department"></select>

Could you please point out where I might be making a mistake?

Answer №1

It is recommended to utilize arr as the representation of a single array element rather than array:

var array = ["Value 1", "Value 2", "Value 3"];

array.forEach(function(arr) {
  $(".department").append('<option value="' + arr + '">' + arr + '</option>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="department" name="department" id="department"></select>

Answer №2

Have you considered approaching it in this way instead:

var choices = list.map(function(item) {
  return '<option value="' + item + '">' + item + '</option>'
});

$(".category").html(choices.join(''))

By using this technique, you can optimize performance by reducing the number of times the DOM is accessed, especially within a loop.

Answer №3

If you want to achieve this using JavaScript, follow these steps:

var array = ["Value 1", "Value 2", "Value 3"];

var select = document.getElementById("department");
array.map(function(item){
var option = document.createElement("option");
option.value = item;
option.text  = item;
select.appendChild(option)
});
<select name="department" id="department"></select>

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 best way to ensure that all recursive calls have completed before proceeding in Javascript?

I am a beginner in reactJS and currently undertaking the challenge of creating a sorting visualizer. I have encountered an issue while working on implementing the quickSort() algorithm. Here is my current quickSort() routine: async quickSort(array, p ...

What is the significance of using composability over the deprecated method in Reactjs Material-UI menuItems?

I have taken over a project that was built using an older version of react, and I am currently in the process of updating it. However, I encountered console errors right off the bat. Error : bundle.js:6263 Warning: The "menuItems" property of the "Left ...

Retrieve the current date and time in JSON format using moment.js for the local

Below is the code snippet I am working with: var startTime = moment("2020-09-08 16:00:00").toDate(); console.log(startTime) const data = {start: startTime} console.log(JSON.stringify(data) After running it, the result is as follows: Tue Sep 08 ...

Creating instances of a class using elements from an array

Let's kick things off by posing this specific question, and then providing the link to the question I'm actually attempting to address at the end. The initial inquiry is as such: Imagine I have an array of arrays, like so: array = [[1, 10, 9], ...

How can I automatically copy a highlighted link in HTML?

I am attempting to implement a feature where users can click on a link and have it automatically copied. For example, I want it to appear like this: "UPI ID: david@okidfcbank". In this case, the link should be highlighted in blue. This is the code I have ...

Tips on setting pre-defined data in a ReactJS form builder field

Currently, I am utilizing the reactjs-form-builder to create forms within a React.js environment. Below is an excerpt of my fields object: this.state = { id: null, loading: true, fields: { "fields&qu ...

How can labels be added when mapping over JSON data?

If I have JSON data structured like this: { "siteCode": "S01", "modelCode": "M001", "modelDesc": "Desc01", "price": 100 "status": "A", "startDate": "Ma ...

Sending image URLs as props in React-Modal might cause an error if not handled properly - TypeError: Cannot read properties of undefined (reading 'map') - so make sure to

Every time I attempt to execute this code, an error pops up: TypeError: Cannot read properties of undefined (reading 'map') This code is supposed to display the image modal, but instead, it's throwing an error. I'm puzzled as to why ...

Acquiring HTML Element Data with Clojure

As a beginner in the world of web development, I have chosen Clojure as my backend language. I am currently in the process of transitioning my user authentication from frontend to backend, and specifically trying to extract the value from an HTML password ...

The function Waterline.create() is not available

Currently in the process of building a basic REST API using Sails.js and Waterline-ORM, I've encountered an issue regarding Post.create is not a function when trying to create an object within the ORM on a Post request. Here is my model: module.expor ...

Can studying Titanium Appcelerator enhance my comprehension of NodeJS?

As I dive into the world of building mobile JavaScript Applications in Titanium Appcelerator, I've come across documentation that mentions the use of the V8 Engine as their JS interpreter for Android. Additionally, some of the approaches seem to be in ...

Utilizing the parameter "error" to distinguish unsuccessful tasks within async.mapLimit

In my coding process, I am using async.mapLimit to implement some parallel operations on an array with a limit of 10: async.mapLimit(files, 10, function(file, callback) { ... etc... }, function(error, files) { ... etc.. }); Within the main opera ...

Navbar Collapse in Bootstrap 5 not functioning properly when losing focus

I am working on a project as a beginner where I am coding a site navbar using Bootstrap 5. The issue I am facing is that currently, the navbar does not collapse when I click away after expanding it. My goal is to make it so that the navbar automatically co ...

When a string containing a space is pushed into an array in Perl, it creates two separate elements within the array

When I try to add a string element with a space into an array in Perl, it splits the string causing two elements instead of one. my @filenames; $filename = "Test Test.test"; push(@filenames, $filename); while (<@filenames>) { print "Here: $_&b ...

Running an Angular-made Chrome extension within an iframe: A guide

I'm currently working on creating a Chrome extension that displays its content in a sidebar rather than the default popup. I've come to realize that in order to achieve this, I need to use an iframe due to the limitations of the default chrome ex ...

"Implementing a feature in AngularJS to dynamically display markers on a Google Map based on latitude and

I am a newcomer to AngularJS and I am attempting to pass my JSON latitude and longitude based on ID into the Google API. Here is the structure of my JSON file: { "totalCount":206, "deals":[{ "id":"2", "Name":"samir", "locations":[{ ...

Every time a button is clicked on the interface, a new element or button will appear. This functionality is made possible through

Currently diving into a new React.js project as a beginner. I have a little challenge in the code snippet below - looking to add a button that displays "Hello World" every time it's clicked using setState. Can anyone guide me on enhancing the DisplayM ...

Responsive div that reacts to scrolling

I am looking for a div that can dynamically change its position as I scroll up or down the page. For example, it could start 30px from the top but then move to 100px as I scroll down further. This div will be located on the right-hand side of my page, clo ...

Avoiding default action on keyboard tab event resets cursor position while typing consecutively

Issue with cursor position resetting to start when tab is the last key pressed I am working on a chrome extension for Gmail using React and need to customize the behavior of the tab key. I have found that using preventDefault and stopImmediatePropagation ...

Using Javascript and ExtJS to retrieve the Codemirror Editor using a textarea

Hello to the wonderful stackoverflow community, I recently incorporated a Codemirror Editor into my ExtJSProject like this: addCodeMirrorPanel: function() { this.getAixmFormarea().add(Ext.widget({ xtype: 'textarea', fieldLabe ...