What could be causing my select element to not display any options after being dynamically generated using JavaScript?

function createDropdown() {
  const selectElement = document.createElement('select');
  selectElement.setAttribute('type', 'text')
  toolresult.appendChild(selectElement);
  const optionElement = document.createElement('option');
  optionElement.setAttribute('value', 'Arial');
  selectElement.appendChild(optionElement);
}

I am encountering an issue with creating the dropdown menu. Even though I have added an option element for Arial inside the select element, the dropdown does not show the option.

// JavaScript Code start
const sheets = document.getElementById('sheets');
const siteDocument = document.getElementsByTagName('body')[0];
const popup = document.getElementById('popup');
const buttons = document.getElementById('buttons');
const toolresult = document.getElementById('toolresult');
const item = document.getElementById('item');

// Popup logic
const myStuff = prompt('Enter \'columns, rows\' NOTE: 5,20 is recommended on computer, refer to documentation.');
let amountOfColumns, amountOfRows;

if (myStuff !== '' || myStuff.includes(',')) {
  const myStuffArr = myStuff.split(',');
  window.amountOfColumns = myStuffArr[0];
  window.amountOfRows = myStuffArr[1];
} else {
  window.amountOfColumns = 5;
  window.amountOfRows = 20;
}

// Create Dropdown function
function createDropdown() {
  const selectElement = document.createElement('select');
  selectElement.setAttribute('type', 'text')
  toolresult.appendChild(selectElement);
  const optionElement = document.createElement('option');
  optionElement.setAttribute('value', 'Arial');
  selectElement.appendChild(optionElement);
}

var counter = 0;
for (var x = 0; x < window.amountOfRows; x++) {
  for (var i = 0; i < window.amountOfColumns; i++) {
    const newInputElement = document.createElement('input');
    newInputElement.width = siteDocument
    newInputElement.style.fontSize = '2vh';
    counter++
    newInputElement.setAttribute('id', 'newElement' + counter)
    console.log(newInputElement.id);
    newInputElement.addEventListener("focus", function doFunctionStuff() {
      changeItem(newInputElement.id)
    }); 
    sheets.appendChild(newInputElement)
    document.getElementById("sheets").style.gridTemplateColumns = "repeat(" + window.amountOfColumns +", 1fr)";
  }
}

var inputs = document.getElementsByTagName("input");
for (var z = 0; z < inputs.length; z++) {
   inputs[z].style.height = "calc((50vh/" +window.amountOfRows +") - 3px)";
}

// CSS Styling
const submitFormula = document.getElementById('submitFormula');
submitFormula.style.fontSize = '1vw';
submitFormula.style.width = '8em';

// Download Excel File Function
var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}
var csvString = csvRows.join("%0A");
var a         = document.createElement('a');
a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
a.target      = '_blank';
a.download    = 'myFile.csv';

document.body.appendChild(a);
a.click();

#titletext {
  font-size: 5vh;
}

#sheets {
  display: grid;
  max-height: 100vh;
}

input {
  min-width: 0px;
  min-height: 0px;
  text-align: center;
}
#buttons > button {
  width: 20vw;
  height: 4vh;
  font-size: 2vh;
}
#itemVisible {
  width: 8vw;
}
#enterFormula {
  width: 8vw;
}
<!DOCTYPE html>
<html>
  <head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>repl.it</title><link href="style.css" rel="stylesheet" type="text/css" /></head>
  <body>
    <div id="popup"></div>
    <h1 id="titletext">Excel Sheets</h1>
    <div id="buttons">
      <button id="" onclick="">File</button>
      <button id="" onclick="">Insert</button>
      <button id="" onclick="">Page Layout</button>
      <button id="" onclick="">Formulas</button>
      <button id="" onclick="">Review</button>
      <button id="" onclick="createDropdown()">Properties</button>
      <button id="" onclick="">Developer</button>
      <button id="" onclick="">Help</button>
    </div> <br>
    <div id="toolresult"></div>
    <div id="item">
      <input id="itemVisible" disabled></input>
      <input id="enterFormula"></input>
      <input type="submit" id="submitFormula"></input>
    </div>
    <div id="sheets" onchange="getItem()"></div>
    <script src="script.js"></script>
  </body>
</html>

If you need the code snippet later:

Answer №1

Here is an updated version of the code with some changes made:

function showProperties() {
  const forButton = document.createElement('select');
  document.getElementById('toolresult').appendChild(forButton)
  const option = document.createElement('option');
  option.value = 'Arial';
    option.innerHTML = 'Arial';
  forButton.appendChild(option)
}

Check out the complete revised code below:

// Some initial element selections
const sheets = document.getElementById('sheets');
const siteDocument = document.getElementsByTagName('body')[0];
const popup = document.getElementById('popup');
const buttons = document.getElementById('buttons');
const toolresult = document.getElementById('toolresult');
const item = document.getElementById('item);

/* Popup */
// Prompts user to enter columns and rows information
const myStuff = prompt('Enter \'columns, rows\' NOTE: 5,20 is recommended on computer, refer to documentation.');

if (myStuff !== '' || myStuff.includes(',') === true) {
  const myStuffArr = myStuff.split(',');
  
  window.amountOfColumns = myStuffArr[0];
  window.amountOfRows = myStuffArr[1];

} else {
  window.amountOfColumns = 5;
  window.amountOfRows = 20;
}

/* Functions */
const itemVisible = document.getElementById('itemVisible');

// Function to change item behavior
function changeItem(test) {
  itemVisible.value = test.slice(test.indexOf('t') + 1, test.length);
}

// Function to display properties
function showProperties() {
  const forButton = document.createElement('select');
  document.getElementById('toolresult').appendChild(forButton)
  const option = document.createElement('option');
  option.value = 'Arial';
    option.innerHTML = 'Arial';
  forButton.appendChild(option)
}

// Loop through rows and columns to create input elements
var counter = 0;

for (var x = 0; x < window.amountOfRows; x++) {
  for (var i = 0; i < window.amountOfColumns; i++) {
    const myNewElement = document.createElement('input');
    myNewElement.width = siteDocument
    myNewElement.style.fontSize = '2vh';
    counter++
    myNewElement.setAttribute('id', 'myNewElement' + counter)
    myNewElement.addEventListener("focus", function doFunctionStuff() {
      changeItem(myNewElement.id)
    }); 
    sheets.appendChild(myNewElement)
    document.getElementById("sheets").style.gridTemplateColumns = "repeat(" + window.amountOfColumns +", 1fr)";
  }
}

// Set height of inputs based on row count
var inputs = document.getElementsByTagName("input");
 for (var z = 0; z < inputs.length; z++) {
   inputs[z].style.height = "calc((50vh/" +window.amountOfRows +") - 3px)";
}

/* Fix Issues OR Bugs */
const submitFormula = document.getElementById('submitFormula');
submitFormula.style.fontSize = '1vw';
submitFormula.style.width = '8em';
submitFormula.style.height = '1.5em';

/* CSS Styling */
#titletext {
  font-size: 5vh;
}

#sheets {
  display: grid;
  max-height: 100vh;
}

input {
  min-width: 0px;
  min-height: 0px;
  text-align: center;
}

#buttons > button {
  width: 20vw;
  height: 4vh;
  font-size: 2vh;
}

#itemVisible {
  width: 8vw;
}

#enterFormula {
  width: 8vw;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Excel Sheets</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="popup"></div>
    <h1 id="titletext">Excel Sheets</h1>
    <div id="buttons">
      <button id="" onclick="">File</button>
      <button id="" onclick="">Insert</button>
      <button id="" onclick="">Page Layout</button>
      <button id="" onclick="">Formulas</button>
      <button id="" onclick="">Review</button>
      <button id="" onclick="showProperties()">Properties</button>
      <button id="" onclick="">Developer</button>
      <button id="" onclick="">Help</button>
    </div> <br>
    <div id="toolresult"></div>
    <div id="item">
      <input id="itemVisible" disabled></input>
      <input id="enterFormula"></input>
      <input type="submit" id="submitFormula"></input>
    </div>
    <div id="sheets" onchange="getItem()"></div>
    <script src="script.js"></script>
  </body>
</html>

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

Using jQuery to eliminate accepting input from form field

Looking to switch between a URL input and file input based on user selection of a radio button. Encountering an issue when attempting to remove the accept attribute from the input, resulting in an Uncaught TypeError: $(...).get(...).removeAttr is not a fu ...

The form submission has been halted as the form is not linked while attempting to conceal the modal using Jquery

I am currently working on a project to submit a form and automatically hide the modal after submission. HTML <div class="overlay"> <div id="popMainWrpDiv"> <div id="closeBtn"><img src="close button img" /></div> <di ...

Can someone explain why I still see a broken image icon despite setting the content-type to "image/jpeg"?

Perhaps this question seems trivial, but I would really appreciate a helpful answer. I am familiar with what an http header is and how it can be modified using the header function in PHP. Let's say I have a PHP file named an_image.php with the followi ...

Issue with external variable not being updated properly in success callback

Working through an array of data, I make updates to a variable called commentBody during each iteration. However, even though the variable is modified within the loop itself, whenever I try to access it from inside a success callback, it consistently show ...

Having trouble finding the sum of values in an array using the Reduce method?

I have always used a 'for' loop to calculate sums in tables, but recently I learned about a better way - using the 'reduce' method. Following documentation and examples with simple arrays was easy enough, but now I am working with an ar ...

Swapping React Components with a Click of a Button

My webpage features a button labeled "Sign Up". Once this button is clicked, I want it to display a new component named "SignUp" in place of the original button. Currently, my method involves using setState to trigger the rendering of the new component upo ...

Continue looping in Javascript until an empty array is identified

Currently, I am in search of a solution to create a loop in Javascript that continues until the array of objects is empty. The object I am working with looks like this: "chain": { "evolves_to": [{ "evolves_to": [{ ...

"Implementing a click event handler on a button within an iframe

On my website, I have embedded an iframe containing external content. Within the code of this iframe is a button identified by the id "XYZ." I want to create an onclick function for this button. Here's what I've attempted: $( "#XYZ" ).click(fun ...

Why is it necessary to separate PHP from HTML?

After exploring comments on various websites, pages, and questions I've asked about the separation of PHP and HTML, I'm curious. Does it mean structuring code like this: <?php myPhpStuff(); ?> <html> <?php morePhpStuff(); ?& ...

Ensure that the image inside a resizable container maintains the correct aspect ratio

I often encounter a situation where I need to showcase a series of thumbnails/images that adhere to a specific aspect ratio within a flexible container. My current approach involves using a transparent, relatively positioned image to enforce the correct as ...

Perform a database query upon clicking a link while simultaneously loading the link's URL

Query: Can a database query be triggered using an <a> tag while still directing the visitor to the <a> tag's URL? One approach could involve directing all links to a specific page that stores the URL of the link. Before redirecting the us ...

The absence of a closing parentheses in the argument is causing an issue when rendering

Apologies for the basic mistake, but I could really use some assistance with this syntax error. I've spent over an hour searching for it and still haven't been able to locate the issue. It seems to be around the success function(data) section. Th ...

"Styling with CSS: Create a sleek border-bottom and background effect

I want to add a bottom border and background color on mouse over. Almost there! In the example below, hovering over the span gives an underline. However, I need the underline to display when entering the hyperlink area. a{ text-decoration: none; paddin ...

Regular expressions tailored for a precise format in JavaScript

Is it possible to create a regex that can validate a specific format? For example, if I have version numbers like v1.0 or v2.0 v1.0 or v2.0 My current regex expression only validates the existence of v, a number, or a .. How can I implement validation ...

What steps can be taken to stop my Bootstrap carousel from overflowing its boundaries?

While constructing my bootstrap portfolio, I encountered an issue with the carousel at the top. It is overflowing and causing horizontal scrolling. Carousel HTML: <div id="carouselExampleIndicators" class="carousel slide" data-ride= ...

Creating a horizontal scrolling section for mobile devices using CSS

Looking to create a horizontal scroll area specifically for mobile devices, similar to the design seen here: https://i.sstatic.net/oSNqL.png Additionally, I want to hide the scrollbar altogether. However, when attempting to implement this, there seem to ...

Retrieve data using ajax within an mvc framework

I am facing an issue where I am unable to receive the data sent with AJAX jQuery to a .NET server as a parameter, modify it in memory, and then convert it to JSON. Any assistance in resolving this problem would be greatly appreciated. JAVASCRIPT document ...

Mastering the art of jQuery UI development, similar to the techniques

I'm currently working on creating an abstraction layer for jQuery UI that enables the definition of Widgets as Objects, similar to ExtJS. Here's how it works: var mydialog = new $.ui.dialog({ modal:true, renderTo:'body', title:'T ...

Exploring various templates with AngularJS Directives

Let's delve into a slightly complex topic, but I'll simplify it as much as possible for you. There is a directive in play: .directive('configuratorRows', function () { return { restrict: 'A', scope: { ...

Exploring the concept of prevState in React components

The object in my class is called "man." man: { name: "John", wife: [{"children": 2}, {"children": 3}] } this.setState(prevState => ({man: prevState.wife[0].children + 1})); I am trying to increase or decrease the quantity of the first wife's chi ...