Guidelines on incorporating several JavaScript functions with variables in a single file

Having some trouble figuring out how to incorporate multiple functions with variables in a single JavaScript file. The syntax is throwing me off.

I'm attempting to follow an example from randomsnippets.com but would like to expand it to allow for additional sections of the form to be added dynamically. I want to avoid cluttering my code with numerous script tags or separate JS files!

In summary, here's what I'm aiming for:


variable a = value
variable b = value

function name(something){
    // operations involving variable a
}

function name(something){
   // operations involving variable b
}

Any guidance on accomplishing this would be greatly appreciated!

<script>
    var counter = 1;

    var limit = 3;

    function addInput(divName){

         if (counter == limit)  {

              alert("You have reached the limit of adding " + counter + " inputs");

         }

         else {

              var newdiv = document.createElement('div');

              newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";

              document.getElementById(divName).appendChild(newdiv);

              counter++;

         }

    }
    </script>

<form method="POST">

     <div id="dynamicInput">

          Entry 1<br><input type="text" name="myInputs[]">

     </div>

     <input type="button" value="Add another text input" onClick="addInput('dynamicInput');">

</form>

Answer №1

It appears there may be an issue related to using global variables in your code. Global variables can cause problems, such as resetting when the page is refreshed leading to inaccuracies. It's advisable to avoid relying on global variables for this reason. Instead, consider dynamically tracking input count.

var limit = 3;

function addInput(divName){

    var counter = 1;
    counter=$( "#"+divName ).children( "input" ).length;

if (counter == limit)  {

    alert("You have reached the limit of adding " + counter + " inputs");

}

else {

    var newdiv = document.getElementById(divName );

    newdiv.innerHTML = newdiv.innerHTML+"<br/>Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";

    document.getElementById(divName).appendChild(newdiv);

    counter++;

}

}

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

Tips for transferring data between functions in component.ts in Angular 2

When I click a button, I am passing some values using "data.someid" and I want to retrieve this value in another button click. html --- <button (click)="click1(data.someid)"></button> <button (click)="click2()"></button> In my com ...

How to use jQuery to hide radio buttons that are not checked when clicking a submit

Looking to dynamically hide all unchecked radio buttons and their labels until a submit button is clicked, displaying only the checked radio button. <form method="post"> <input type="radio" name="radiobtn"> <label for="first">Fir ...

Connecting two browser peers through js-ipfs

I am currently working with two desktop PCs, each running a browser tab that is using js-ipfs to instantiate an IPFS node. //file index.html, served through HTTPS const node = IpfsCore.create(); //ipfs browser node Both nodes have peers (approximately 50 ...

The Angular application sent an OPTIONS request instead of a POST request via HTTP

I'm encountering CORS errors while attempting to send HTTP requests from my angular.js application to my server. The code used to make the HTTP request is as follows: functions.test = function(foo, bar) { return $http({ method: 'POS ...

A secure method for dynamically adding a JavaScript file

In my lang folder, I store language variables for a website. To dynamically include the desired file based on the user's language selection, I use session variables. For example, if the user selects English, 'en' is stored in the lang variab ...

What is the best way to perform a redirect in Node.js and Express.js following a user's successful login

As I work on developing an online community application with nodejs/expressjs, one persistent issue is arising when it comes to redirecting users to the correct page after they have successfully signed in. Despite reading several related articles and attem ...

In Stripe.js, the background color and height of the credit card input cannot be customized

I'm struggling with customizing the appearance of a Stripe credit card input within my Vue.js application. I want to adjust the background color to #f1f1f1 and set the height to 60px, but despite trying both base styles and css, I can't seem to g ...

Rotating the camera around the origin in Three.js

Hey, I'm having some trouble with what I thought would be a simple task. I have a group of objects at the origin, and I'm trying to rotate a camera around them while always facing the origin. According to the documentation, this code should work: ...

The function data() is coming back as null

This is the code snippet I am working with: $.getJSON("link here", function (result) { $.each(result, function (i, value) { $('.usersOfGroupList').append($("<li id='userElement' data-userId='' ></li>") ...

Updating the index of an array in MongoDB using Node.js proves to be a challenging task

Currently, I am working on creating an API for a bus ticketing system. However, I am facing difficulties in getting it to function properly in Node.js. [ { "id":1, "hour" : "7:30am" , "seats" : [ 0 , 0, 0, 0, 0 , 0, 0, 0, 0 , 0 ...

Converting database data into an array of objects using JavaScript

In my App.js file, I have the following code: const getPlayers = async()=>{ const players = await API.getPlayers(); setPlayers(players) } getPlayers() The following code is from my API.js file: const getPlayers = async() => { return getJson( ...

The instance does not have a defined "key" property or method in this Vue/Laravel application

When I attempt to delete a register in my application, I encounter a Vue-warn message: The property or method "key" is referenced during render but is not defined on the instance. Make sure that this property is reactive by initializing it in the data o ...

Ways to customize the TextInput component in React-Admin

I am facing a challenge with overriding specific fields in my custom theme. It seems that setting the custom theme also overrides other fields unintentionally. I attempted to use useStyles to resolve this issue, but unfortunately, it did not work as expec ...

How can I create a vertically scrollable table body using material-ui?

Is it possible to create a scrollable table body if the height property does not apply to the tbody element? const styles = { tableBody: { height: 300, overflow: "auto" } }; <Paper className={classes.root}> <Table> < ...

How can I retrieve x-data from an external file using Alpine.js?

I recently started exploring Alpine.js and grasped the fundamentals, but I'm facing challenges when trying to move functions outside of inline script tags. Consider this snippet from index.html: <div x-data="{ loading: false }"/> &l ...

Implementing a custom arrow icon and adding functionality for closing on click in Kendo Multiselect

I'm looking to enhance the functionality of my Kendo Multiselect by giving it the appearance and behavior of a standard dropdown list. I'd like to include an arrow or triangle icon that toggles and closes the list when clicked. Can anyone provide ...

`Enhancing Navigation Links with Scroll-Activated Styling`

I'm attempting to recreate a visual effect that is similar to: Specifically, I am trying to achieve a style where the links in the navigation bar change color when the corresponding section is displayed, such as having the gallery link in the navbar ...

Struggling to get a basic HTML form to function with JavaScript commands

In my form, there are two input fields and a button. Upon clicking the button, a JavaScript function is triggered which multiplies the values entered in the inputs. The result is then displayed in a <p> element and evaluated through an if else statem ...

Ways to display a US map using d3.js with state names positioned outside each state and pointing towards it

Currently, I am working with d3.js and d3-geo to create a map of the USA. My goal is to display the names of some states inside the state boundaries itself, while others should have their names positioned outside the map with lines pointing to the correspo ...

What is the best method to retrieve a specific data field from a JavaScript object using jQuery?

I am new to the world of jQuery and JavaScript and I am unsure if this question has been asked before. Despite searching extensively, I have not found a relevant answer to my specific query. My goal is to create a web crawler using Apify. I am looking to e ...