-1

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 createQuestions() 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()">
j08691
  • 204,283
  • 31
  • 260
  • 272
Tim
  • 106
  • 6
  • You should be able to access the `number` variable anywhere if you define it globally. The when you run your `createQuestions()` function you can assign it to a value. Can you post the rest of your JS here? It would be helpful to fully solve the problem. – Coleman Jun 23 '16 at 20:00
  • Possible duplicate of [Define global variable in a JavaScript function](http://stackoverflow.com/questions/5786851/define-global-variable-in-a-javascript-function) – But those new buttons though.. Jun 24 '16 at 00:25

2 Answers2

2

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 () {
    alert(global1);
}
Community
  • 1
  • 1
keiv.fly
  • 3,343
  • 4
  • 26
  • 45
  • But when I call that function setGlobal() on a button click, the variable will not be declared, since the button click is calling ONLY the function.. – Tim Jun 23 '16 at 20:04
  • You may not declare it inside the function, but you can reassign the variable. And it will be accessible, because it is global. – keiv.fly Jun 23 '16 at 20:06
  • Aha! There we go, this is exactly what I needed. I wonder why I never thought of this. Thanks! – Tim Jun 23 '16 at 20:10
1

It is not possible to access a function's local variables from outside of that function, so you have four options:

  1. Declare a global variable!
  2. Write a separate function that grabs the value for you
  3. Create an object that contains the value you need
  4. Grab the value from within your new function using getElementById()