The JavaScript function does not recognize the global variable when invoked within an onClick event

When a button is clicked in an HTML form, I want to show the user input by calling a JavaScript function. However, I am facing an issue where the function does not recognize the variable unless it is defined inside it.

Here is the HTML and JS code snippet that demonstrates the problem. The code can be viewed here:

<p><label>Name:</label>
<input type="text" name="userName" id="userName" placeholder="e.g John Lewis"/> 
</p>
    
<input type="submit" name="submitButton" value="Display" onclick="run()"/>
<p>Name Provided: <label id="outputUserName"></label></p>


var userName =  document.getElementById("userName").value;
function run() {document.getElementById("outputUserName").innerHTML = userName;}

The function works if I directly write the code to fetch the user input inside it:

document.getElementById("outputUserName").innerHTML = document.getElementById("userName").value;

Alternatively, I can define the variable inside the function to make it work, but I require the variable to be global for use in multiple functions without repeated definitions.

Answer №1

The issue here is that the function is unable to recognize the variable unless it is defined within it.

Actually, the variable is recognized, but it may not have the desired value.

The problem arises when you attempt to access the input value before any user input is received. In this case, the variable userName will only contain an empty string. You can confirm this by setting a default value for the input:

<input type="text" name="userName" id="userName" value="default value"/>

DEMO

To access the input value when needed, it is important to do so at the right moment. As a workaround, you can maintain a global reference to the DOM element:

var userName =  document.getElementById("userName");
function run() {
    document.getElementById("outputUserName").innerHTML = userName.value;
}

It is also worth noting: Why does jQuery or a DOM method such as getElementById not find the element?

Answer №2

One important thing to keep in mind is the placement of your script tag in relation to the body content. Ensure that it is loaded after the page content or encapsulate your code within an on ready function to guarantee that the page has fully rendered. If the script is positioned before the actual

element, the command <code>document.getElementById("userName");
will return null because the browser has not yet rendered the element. This can be confirmed by checking your console for any errors.

Uncaught TypeError: Cannot read property 'value' of null

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

Issue encountered when attempting to insert data via node into MySQL database

As a new Node developer, I am in the process of building some initial applications. Currently, I am working on inserting records into a MySQL database using Node. Below is an example of my post method: router.post('/add',function(req,res){ c ...

Having trouble parsing JSON with Ajax in Pusher using PHP?

I am facing an issue while sending multiple parameters using the Pusher AJAX PHP library. This is the error I encounter: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Here is my PHP and JS code: <script src="https: ...

If the checkbox is selected, the textbox will receive the class "form-input validate required" upon Jquery validation

I am using Jquery Validation plugin to validate a form on my website. Below is the HTML form code: <form id="caller"> <label>Phone:</label> <input type="text" name="phone" id="phonen" class="form-input" value="" /> <di ...

Adding a regional iteration of a library that was unable to be loaded

Recently, I have been experimenting with PhantomJS to capture screenshots of a webpage every five minutes. While the process runs smoothly most of the time, I encountered an issue where the AngularJS library fails to load intermittently. This results in th ...

Angular Promises - Going from the triumph to the disappointment callback?

It seems like I might be pushing the boundaries of what Promises were intended for, but nonetheless, here is what I am attempting to do: $http.get('/api/endpoint/PlanA.json').then( function success( response ) { if ( response.data.is ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

The charAt function in a basic JavaScript if statement is failing to execute

When a user inputs a number that does not start with 6 or 9, an error occurs: console.log($(this).val().charAt(0)); if($(this).val().charAt(0) != 6 || $(this).val().charAt(0) != 9){ x=false; }else { x=true; } The console.log function corre ...

Is it necessary to utilize body-parser in our code?

In my research, I've noticed that many tutorials recommend using both express.json and bodyParser.json middleware. But aren't they essentially performing the same function? ...

Check to see if the item is not already in the cart, and if so, add it and then increase its quantity

Utilizing React context, I have implemented a simple logic to add products to the cart using the useReducer hook for adding items. If we look at the Redux Toolkit implementation, here is my redux logic: const cartItemSlice = createSlice({ name: " ...

Having trouble viewing the image slider on an HTML webpage

I've been attempting to incorporate an image slider into my personal website on GitHub, but I've encountered some difficulties as the images are not displaying. Interestingly, I can load individual images without using the slider and they show up ...

When attempting to retrieve information using the findById(''), the process became frozen

When attempting to retrieve data using findById(), I'm encountering a problem. If I provide a correct ObjectID, the data is returned successfully. However, if I use an invalid ObjectID or an empty string, it gets stuck. If findById() is called with a ...

What is the best location to insert the code for toggling the text on a button?

I'm looking to update the button text upon clicking. When the button is clicked, the icon changes accordingly. I want the text to change from "Add to list" to "Added to list". I attempted to implement this functionality with some code, but I'm un ...

What could be the reason for the onClick event functioning only once in HTML?

Below is the code snippet containing both HTML and JavaScript. However, the issue I am facing is that the onclick event only seems to work for the first <li>. <!DOCTYPE html> <html> <body> <ul class="list"> <li ...

Guide to using AJAX for the GraphHopper Matrix API

I am struggling to send this JSON with the required information because I keep encountering an error during the request. message: "Unsupported content type application/x-www-form-urlencoded; charset=UTF-8" status: "finished" I'm not sure what I&apos ...

Accessing a peaceful API and displaying the outcome on a webpage using Node.js

I am currently working on a project that involves fetching data from a RESTful API and displaying the results on an HTML webpage using Node.js. While my code is running smoothly, I would like to ensure that the RESTful request is made every time the webp ...

Having trouble running tests on the Express.js server

I'm struggling to run basic tests on my expressjs server and close it immediately. I have exported the server as a promise, but can't seem to figure out how to achieve this. Below is the code for my server file : index.js const config = require( ...

The unresponsive sticky navigation bar on a Joomla website is causing issues

I recently launched a new website that can be found here. The site includes the following JavaScript code: $(document).ready(function(){ $(window).bind('scroll', function() { var navHeight = $( window ).height() - 70; ...

Tips for enhancing a search algorithm

I am currently working on implementing 4 dropdown multi-select filters in a row. My goal is to render these filters and update a new array with every selected option. Additionally, I need to toggle the 'selected' property in the current array of ...

Ways to implement a percentage for scrollTop

I'm currently troubleshooting the code below. My goal is to understand why I'm unable to scroll the .post div with jQuery and input range properly using a percentage value like this: $("[type=range]").on('input',function(){ var v ...

Developing a unique JavaScript object by extracting information from a jQuery AJAX response

Is there a recommended approach for creating a custom JavaScript object that contains data retrieved from a jQuery AJAX request? I'm considering two methods, but unsure which is the most appropriate. The first method involves including the AJAX reques ...