Tim Nguyen Tim Nguyen - 1 year ago 50
HTML Question

Accessing variable from different function

I have the following code in HTML which creates a button, that when clicked creates some questions in my page, works fine.

<input type="number" name="quantity" id="num_questions" min="1" max="99"><br>
<input type="button" name="go" id="go_button" value="Go" onclick="createQuestions()"><br>

However, within my function
I have defined a variable in JavaScript, which is based on a number input from my HTML code, shown above.

var number = document.getElementById('num_questions').value;

I have another button which calls a separate function but I need that variable number I locally defined in another function. Is there any way I can grab that variable and use it globally? I tried defining it outside my function, but since the onclick event only calls that one function, it won't create the variable.

Other button:

<input type="submit" name="submit" value="Create Tree" onclick="displayData()">

Answer Source

According to How to declare a global variable in a .js file you can define a variable before any function is called and then use it in different functions.

var global1 = "I'm a global!";

function setGlobal () {
    global1= document.getElementById('num_questions').value;
function testGlobal () {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download