What is the process for receiving user input and appending it to an array in JavaScript?

I'm currently working on a page that takes user input, adds it to an array, and then creates a select and option list from that array.

<!DOCTYPE>
<html>
<head>
<script>
 var optionList = [];
 for (var i = 0; i < optionList.length; i++){
  var opt = optionList[i];
  var option = document.createElement("option");
  var select = document.getElementById("select");     
  option.setAttribute("id", opt);
  option.setAttribute("class", "intersect-option");
  option.value(opt); 
  select.appendChild(option);

} 
function addOption(){
var name = document.getElementById("name").value;
name.push(optionList());
}
</script>
</head>
<body>
 <input type="text" id="name" value="">
 <input type="button" onclick="addOption()" value="Add Person">
 <select id="select">
</select>

</body>
</html>

The problem I'm facing is that when I try to input information, I get the following error message:

Uncaught TypeError: optionList is not a function

at addOption (selectTest.html:19)

at HTMLInputElement.onclick (selectTest.html:25)

I'm unsure of what I'm doing wrong, and any assistance would be greatly appreciated.

Answer №1

It's recommended to add the name variable to the option_list array. The proper syntax for this operation is option_list.push(name);

function add_option(){
    var name = document.getElementById("name").value;
    option_list.push(name);
}

Answer №3

name.push(option_list());

In this context, if option_list is not defined as a function, attempting to call it using parentheses would result in an error since it is invalid syntax in C family languages.

Furthermore, looping from zero to the length of an empty array (which is zero) may not produce the desired outcome. It's important to consider the logic behind such loops for the intended functionality.

Answer №4

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE>
    <html>
    <head>

    </head>
    <body>
     <input type="text" id="name" value="">
     <input type="button" onclick="add_option()" value="add person">
     <select id="select">
    </select>
    <script>
     var option_list = [];
       // for loop at thats option_list to select select tag

     
      var select = document.getElementById("select");     

    function add_option(name){
    var name = document.getElementById("name").value;
     var option = document.createElement("option");
      var label = document.createTextNode(name);
      option.setAttribute("id", name); 
      option.setAttribute("class", "intersect-option"); 
      option.value = name; 
      
      option.appendChild(label);
      select.appendChild(option);

    }



    </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

Successful Ajax request made within a loop to update a global variable

I am trying to set a global variable from a function and loop through AJAX calls to get the distance. However, I'm facing an issue where the nearestIndex variable always ends up being undefined. The first solution I came across was to use async: fals ...

What is the best way to insert a button at the end of the last row in the first column and also at the

I am working on a JavaScript project that involves creating a table. My goal is to dynamically add buttons after the last row of the first column and also at the top of the last column. for (var i = 0; i < responseData.length; i++) { fo ...

Navigating to various controller bases depending on the type of route value in a node.js application: How is it

As I work on organizing my URLs, I have implemented a consistent pattern for my routes. Below are the routes I've set up: app.route('/inbox') .get(user.inbox); app.route('/:messageId') .get(user.message); I am looking f ...

Enrich an HTML table using jQuery based on an indentation pattern

                 Overview: Currently, my colleague and I are working on developing an inventory control system using the Django Framework within our department. While most aspects of the system are operational, we are encountering ...

What is the reason behind the shifting behavior of e.currentTarget when using event delegation in jQuery?

Click here for the code snippet <div id="container"> <button id="foo">Foo button</button> <button id="bar">Bar button</button> </div> $('#container').on('click', function(e) { var targ ...

Issues with closures in JavaScript

Struggling to grasp closure with 3 levels of scopes. https://jsfiddle.net/Ar2zee/wLy8rkyL/1/ How can I retrieve the value of parameter "g" within the level3 function? var a = 10; function level1(b) { var c = 1; function level2(f) { var d = 2 ...

Unable to trigger button retrieved through ajax request

I am facing a minor issue with my php page. It returns a button using ajax, as you can see below: HTML snippet: <a href="#" class="unit_register_button"> Register </a> jQuery code: $('a.unit_register_button').click(function(e) ...

Replacing multiple attributes within a complex HTML opening tag using Node.js regular expressions

I'm currently working on a Node.js project where we need to search through several PHP view files and replace certain attributes. My goal is to extract the values of HTML open tag attributes and replace them. To clarify, I want to capture anything in ...

Issue with Material UI Autocomplete not displaying updated options

I'm working on implementing API calls to my backend to retrieve suggestions as the user types into an input field. The current code I have is as follows: const dispatch = useDispatch(); const [ fromOptions, ] = useSelector(({ search: { fromOptions ...

Bringing a TypeScript module to life with a sprinkle of 'import

I am attempting to integrate the numbro JavaScript library into my TypeScript project. The numbro.d.ts file exports like this: declare const numbro: NumbroStatic; export default numbro; My simple import statement looks like this: import numbro from &apo ...

Scraping the Web with Python: Harnessing the Power of Selenium and

Seeking assistance with a problem I've encountered. I'm attempting to extract numbers from a specific website (link provided in the code below). Since the website utilizes JavaScript, my approach involves using selenium to load the page first and ...

Pressing the button will activate the Ctrl+z and Ctrl+y key commands

I have created two separate buttons for triggering actions equivalent to pressing Ctrl+z and Ctrl+y. I am attempting to make these actions occur with the click of a single button. However, when trying to set up the functionality to trigger Ctrl+z and Ctr ...

AngularJS ng-click function not functioning as expected when used within ng-repeat

The event.id is correctly displayed in the html text, but the function does not receive it properly. Even though it appears correctly in the source code, there seems to be an issue here. <span ng-repeat="event in [{"id":"dxczhlyvmblc","name":"4 on 4 - ...

Once the grunt build process is complete, execute "heroku run fileName" to launch the

In order to gain a deeper understanding of Heroku scheduling, I decided to delve into an informative post on the topic and followed the instructions provided to build the app. The highlight of the post was when I successfully executed heroku run numCheck a ...

Trouble with CSS animation when incorporating JavaScript variables from a PHP array

Whenever I use a script to fetch an array of objects from PHP... I successfully display the results on my website by outputting them into Divs. The challenge arises when I introduce CSS animations. The animation only triggers if the variable length excee ...

Using Inline Styling to Showcase a Background Image in a REACTJS Component

import React from 'react'; import Slick from 'react-slick'; import style from './Slider.module.css'; import {Link} from 'react-router-dom'; const SliderTemplates = (props) => { let template = null; const ...

The Express middleware is not being utilized

There seems to be an issue with the middleware in the code below that is supposed to create a property req.user if req.session.user exists. Unfortunately, it appears that the middleware is not being triggered, causing 'hihihhiihi' to not be print ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

A more efficient method to retrieve every possible combination in ascending order of length while also conserving memory

Seeking to find all possible combinations of listA in ascending order by length. While I have successfully achieved this task, the current code I am using results in a Memory error when the list size exceeds 1000. What approach can I take to accomplish thi ...

Steps for implementing a click event for a navigation drop-down using an HTML helper class

In my MVC 5 application, I have implemented a navigation dropdown. Here is the code snippet: <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="menu> Report ...