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.