0

I am trying to set and get the value of a global variables. Here is the jsfiddle

HTML

<input type="button" value="setValue" onClick="setValue()">
<input type="button" value="getValue" onClick="getValue()">

JS

//setting global variable
var theValues = '';

function setValue() {
    theValues = "test";
    alert(theValues);
}

function getValue() {
    alert(theValues);
}

But it is not throwing an error and not working

Community
  • 1
  • 1
user3191304
  • 221
  • 3
  • 8

2 Answers2

3

You have to change your jsFiddle setting to allow your code to truly be in the global namespace. Right now, your code is in an onload handler and is thus not global and so the event handlers specified in your HTML are not found and thus never called.

In the upper left of your jsFiddle, change the drop-down that says "onLoad" to be "No wrap - in head". Then, your jsFiddle will work as it does here:http://jsfiddle.net/r8fsh3ek/2/.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

You can do like this also

<input type="button" value="setValue" onClick="setValue()">
<input type="button" value="getValue" onClick="getValue()">

Your javascript code :-

var theValue= '';
 function setValue() {
   theValues = "test";
    alert(theValues);
     return theValues;
}

function getValue() {
    theValues = setValue();
    alert(theValues);
  }
Saurabh
  • 101
  • 1
  • 8