A guide on adding an option to a dropdown menu in HTML

I have a variable that stores a number. My goal is to dynamically add options to a select element based on the value of this variable. For example, if the variable equals 10, I need to append 10 options to the select element with each option displaying the next numeric value, starting from 1. Initially, there is one hard-coded option in the select element, and then additional options need to be added using JavaScript. However, I've encountered an issue with the scripts I've tried, as I keep receiving an error message stating "cannot use 'in' operator to search for length."

https://jsfiddle.net/v1yyhfm8/

HTML

<select id="main">
    <option selected>1</option>
</select>

I attempted the following:

var total = dataSource.total();
for (var i = 2; i <= total; i++) {
    var added = document.createElement('option');
    var test = $('#main');
    added.value = i;
    added.innerHTML = i;
    test.append(added);
}

and

var total = dataSource.total();
$.each(total, function (i, item) {
    $('#main').append($('<option>', {
        value: item.total,
        text: item.text
    }));                               
});

Answer №1

To prevent an infinite loop in your code, make sure to update the for loop condition to i <= total.

var total = dataSource.total();
for (var i = 1; i <= total; i++) {
    var added = document.createElement('option');
    var select1 = $('#main');
    added.value = i;
    added.innerHTML = i;
    select1.append(added);
}

var total = 10;
for (var i = 1; i <= total; i++) {
  var added = document.createElement('option');
  var select1 = $('#main');
  added.value = i;
  added.innerHTML = i;
  select1.append(added);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="main">
  <option selected>1</option>
</select>

Answer №2

Sample Code:
 <select id="main">

 </select>

 Jquery Function:


  var opt = ' <option selected>1</option>';
  for(var i = 2; i<= 10; i++){
    opt += ' <option>' + i + '</option>';

  }
  $("#main").append(opt);

Visit Jsfiddle to view the code in action: https://jsfiddle.net/v1yyhfm8/

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

Transforming an array of HashMaps into a JSON object within a servlet and showcasing it on a JSP page

Looking to extract all table rows and store them in an array of hashmaps, then convert them into a JSON object to be sent to a JSP page using Ajax and jQuery. Struggling with displaying the content on the JSP page. I've written the code below but need ...

Regular expressions to eliminate leading zeros from a string, excluding those that are part of decimals

Looking for a JavaScript regex that can remove any leading 0 in a string if the string is an integer. 0 => '' 0000 => '' 001 => 1 0.11 => 0.11 0000.11 => 0.11 11000 => 11000 I've been attempting to solve t ...

Issue 404: Trouble sending form data from React to Express

I'm facing an issue when trying to send form data from a React frontend to my Node.js/Express backend. The problem seems to be related to a 404 error. I've included only the relevant code snippets below for reference. Function for submitting the ...

What is the best way to handle my JavaScript libraries in Grunt - Bower or NPM?

After diving into Grunt, I've come to realize how amazing it can be. However, I have one concern when it comes to managing Javascript libraries. Currently, my workflow involves searching for each library online and placing them in a js/libs folder. Th ...

What is the best way to bypass TS1192 when incorporating @types/cleave.js into my Angular application?

Using cleave.js (^1.5.2) in my Angular 6 application, along with the @types/cleave.js package (^1.4.0), I encountered a strange issue. When I run ng build to compile the application, it fails and shows the following errors: ERROR in src/app/app.component. ...

Using jQuery.dataTables to choose all rows except the final column

I'm utilizing a table with jQuery.dataTables. I have a requirement to input dates in the last column. However, when I click to input a date, the row becomes deselected. The following code is meant for selecting all rows: Displayed below is the DataT ...

Scrolling background for a nested Bootstrap modal

I am facing an issue with a modal that has a lengthy content and a button to open another modal. Once the inner modal is closed, the outer modal becomes unresponsive. It fails to scroll and instead, the background starts to scroll. While I have come acros ...

Exploring Shader Materials and OpenGL Framebuffers within the realm of THREE.js

In my current project, I am attempting to utilize an FBO within a material in THREE.js. The project involves a GPU-based fluid simulation that generates its final visualization to a framebuffer object, which I intend to use as a texture for a mesh. Below i ...

Adding ng-add & npm link - A guide to mocking the npm registry

I'm currently working on a collection of schematics for @angular/cli and I want to test it locally. Is there a way to test the ng-add CLI feature locally? When I link my project using npm link and run ng add myFeature, @angular/cli attempts to downl ...

Utilize Bootstrap 4 classes to center divs horizontally in the container at the top, middle, and bottom

I'm having trouble finding the right way to center the div elements horizontally. .d-flex.flex-row.justify-content-center div.align-self-start p Top div.align-self-center p Middle div.align-self-end p Bottom http ...

The scroll bar is acting peculiarly when the height is adjusted

I need assistance creating a chat widget that has a maximum height for the entire chat and allows the content to fill in without specifying fixed heights within the chat itself. Below is my code: HTML <section class="boxlr-chat"> <div class= ...

Having trouble getting the Google motion chart to work with asynchronous JSON requests

I have been using the code below to make a request for a JSON file and then parsing it. google.load('visualization', '1', {packages: ['controls', "motionchart", "table"]}); google.setOnLoadCallback(function(){ createTable($(& ...

How can I position my navbar above my background image using Bootstrap?

I am a newcomer to using bootstrap and I am attempting to create the following design: https://i.sstatic.net/EV9A1.png In the design, the navbar is situated on top of the background image. However, with my current setup, this is what I have: <!DOCTYPE ...

Pictures displaying various shapes in contact with each other

I have a unique challenge involving an image that has been physically cut into puzzle-shaped pieces. Is there a way to align these individual puzzle pieces using only HTML and CSS to create the illusion of a single cohesive image once assembled? It' ...

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Having trouble locating the module while importing MP3 files in a React project

UPDATE The issue stemmed from my limited understanding of the environment I was working in, but the responses provided below may be helpful for others facing similar challenges. EDIT: It appears that there is a problem with trying to import an mp3 file in ...

As the div elements stack up and you scroll towards the top or bottom

I am dealing with two nested DIVs that are both scrollable. When I scroll the "inside div" (the green one in the attached file), and reach the bottom of the DIV, it starts scrolling the DIV beneath it. How can I prevent the DIV beneath from scrolling only ...

Reorganizing data with JSON using JavaScript

I have a JSON data that I am parsing with NodeJS and I need to restructure it into a different JSON format. The original JSON includes multiple "pages" objects within the "rows" object, each containing similar keys and values except for the "values" and "d ...

Tips for retaining focus on the same control following an asynchronous postback

I am experiencing an issue with my 3 textboxes, where one is placed in an update panel that refreshes every 4 seconds. Unfortunately, during the refresh process, the focus on controls outside of the update panel is being lost. I need a solution to maintain ...

How can the Jquery UI Datepicker value be automatically set upon redirecting to this page?

When I submit a form and an error occurs, the value selected in the datepicker is not retained. The datepicker field remains empty. How is this possible? <html> <head> <script type="text/javascript" >. $(function() { ...