What could be the reason for my user input not being captured and saved as variable data on the HTML webpage?

Here is the code I am working with:

var g = document.getElementById("al").value;

function start() {
  document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g);
}
<p id="test2">Output will be displayed here:</p>
<form>
  <label for="g">a:</label>
  <input type="number" id="al" name="g" placeholder="Enter a" value="55">
  <button onclick="start()" type="button">Click Here</button>
</form>

When I click the button, the output shows "string55", regardless of user input. How can I correct this to display the actual user input instead of static value 55?

Answer №1

To retrieve the value from a function, you must access it within the function:

function start() {
  var g = document.getElementById("al").value;
  document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g);
}
<p id="test2">Output is displayed here:</p>
<form>
  <label for="g">a:</label>
  <input type="number" id="al" name="g" placeholder="Enter a" value="55">
  <button onclick="start()" type="button">Click Here</button>
</form>

Note: Using inline HTML on* handlers is considered poor programming practice. It can be difficult to debug. JavaScript should ideally be in one centralized location. Instead, consider using Element.addEventListener().

const elBtn = document.querySelector("#start");
const elTest = document.querySelector("#test2");
const elG = document.querySelector("[name=g]");

const printGValue = () => {
  const g = elG.value;
  elTest.textContent = typeof(g) + parseFloat(g);
};

// Execute on click
elBtn.addEventListener("click", printGValue);
// Also execute on initialization:
printGValue();
<form>
  <label>a: <input type="number" name="g" placeholder="Enter a" value="55"></label>
  <button id="start" type="button">Click Here</button>
</form>

<p id="test2"></p>

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

I am looking to showcase a series of icons linked together by connecting lines

I have successfully designed the layout and added icons, but I am facing difficulty in creating connecting lines between them. I attempted to utilize CSS borders and pseudo-elements, yet I cannot achieve the desired outcome. If anyone could offer a CSS-ba ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

Error: The system reference 'Sys' is not defined in ASP.NET

I am trying to implement ajax functionality on the ASP.NET platform. To achieve this, I am using ScriptManager in conjunction with jQuery, and adding the script after the "document is ready" event. $(document).ready(function () { // sync {{scopeN ...

How can I ensure my function waits for a promise to be resolved using Async / Await?

I'm running into an issue where I want my function to keep executing until the nextPageToken is null. The problem occurs when the function runs for the first time, it waits for the promise to resolve. However, if there is a nextPageToken present in th ...

Find and Scroll Dropdown Menu with Bootstrap Framework

Access the jsfiddle for more information. Have a look at these questions: In my dropdown menu, I have included a search box and multiple sub-menus. However, the search box only filters the first dropdown menu and does not work with the sub-menus. How ca ...

What is the process for adding a line of JavaScript directly into the code (instead of using an external .js file)?

I am trying to insert a script tag that will run one line of JavaScript directly into the head of a document instead of inserting an empty script tag with a src attribute. So far, I have the following code: <script type="text/javascript"> var script ...

How can I effectively display personalized information from an MSAccess database on a WordPress website?

I am seeking advice from experienced Wordpress developers. My organization possesses an internal MS Access database that comprises various tables, reports, and input forms. The structure of the database is relatively straightforward, encompassing informati ...

When using the GET method to load a PHP file via AJAX, the page may not display certain jQuery plugins even after the file

Hello, I am a beginner learning AJAX and JQuery. Maybe this is a silly question, but please bear with me. I am trying to dynamically show data without refreshing the page using AJAX. I have a function loaded in the body tag which handles this. Everything ...

How to use React MUI Checkbox to set the checked value as false

I'm encountering an issue with the React MUI - Checkbox component. On my site, I have a checkbox linked to a handler that targets a REST API endpoint. This endpoint sets a boolean flag for the user in the database on a POST request and returns the boo ...

Navigating URLs with Ajax Requests in CakePHP

How can ajax calls in javascript files located in the webroot be handled without PHP interpretation? In my project using CakePHP and require.js, I avoid placing javascript directly in views. To address this issue, I set a variable in the layout to store t ...

Unable to run a Bash script using PHP

I'm currently facing a challenge while attempting to run a simple Bash Script from within a PHP script. The process involves collecting data from an interactive HTML5 front-end page, transmitting it through ajax to the PHP script, parsing the variable ...

Utilizing Jquery for Mouse Clicks

Is there a way to simulate a mouse click using jQuery? <div id="myId> Simulate Mouse Click programatically</div> I currently have a mouse listener set up. $("#myId").mousedown(function(){ alert("Mouse clicked programatically"); }) ...

Struggling to effectively customize a bootstrap theme

After incorporating a custom .css file from an internet theme that overrides some bootstrap properties, I noticed that it works in certain scenarios. However, when attempting to modify the primary color in the :root{} section of the styles.css file, the ch ...

The app.use function encountered an error stating "Cannot modify header information - headers already sent"

Within my app.js file, I have the following code snippet: app.use(function(req, res, next){ if(!req.user){ res.redirect('/login_'); } next(); }) Upon reviewing the above code, everything appears to be correct. In my route/index.js fi ...

Having trouble choosing elements with angular.element within ng-repeat loop

In my HTML code, I am using an ngRepeat element: <ol id="animationFrame"> <li ng-repeat="animationImage in animationImages" ng-repeat-listener> <img ng-src="{{animationImage.src}}" id="{{animationImage.id}}"> </li> </ol& ...

What steps should I take to resolve the "You do not have authorization to access this directory or page" error in Azure App Services?

Currently, I am attempting to deploy my Next.js 13 application to AppServices using Github Actions. The compilation process on Github was successful, however, I am encountering an issue where my application does not seem to be deploying or starting up prop ...

What is the best way to design a circular icon using OpenLayers?

I am currently incorporating openlayers into my ionic app and working on placing users on the map. I have encountered a problem as I am unsure how to apply custom CSS styling to the user element, which is not directly present in the HTML. In the screenshot ...

Modify the color of the Swing link label for disabled state

I'm currently working with Java Swing linkLabel. I've noticed that when the link is disabled, it appears in gray by default, but I would like it to be black instead. Is there a method available to change the color of a disabled link label? ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...

Discover the magic of triggering events that dynamically alter CSS styles

I am trying to implement an eventBus in the App.vue component that allows me to change a modal's CSS based on a payload object. For example, if I pass { type: 'success' }, the border of the modal should turn green, and if I pass { type: &apo ...