I am using javascript onclick attribute. How to use a global varibale in that? Global variable in JS file:
var globalVar;
globalVar = "Some String";
Now i want to use the above string my jsp page:
<a href="#" onclick="myFunction(globalVar)">Link</a>
But its just passing as string i.e., the parameter is just passing as globalVar as a string but not its value. Can any one tell me how to apply this global variable value inside the attribute?
I am using javascript onclick attribute. How to use a global varibale in that? Global variable in JS file:
var globalVar;
globalVar = "Some String";
Now i want to use the above string my jsp page:
<a href="#" onclick="myFunction(globalVar)">Link</a>
But its just passing as string i.e., the parameter is just passing as globalVar as a string but not its value. Can any one tell me how to apply this global variable value inside the attribute?
globalVar
, you can even access its value in myFunction
. You don't need to pas it as argument. It is already available to every function
– Muhammad Usman
Commented
Nov 1, 2017 at 4:05
you can use alternate way like this in html
<a href="#" onclick="myFunction()">Link</a>
in javascript
<script>
var globalVar='somestring';
function myFunction(){
console.log(globelVar);
}
</script>
Global arguments can be referenced inside an onclick
function. Example:
var test_value = 3;
function test(val){
console.log(val);
}
<a onclick="test(test_value)">TEST </a>
Wrap them in a function like myFunction1(), and change it to:
<a href="#" onclick="myFunction1">Link</a>
....
....
function myFunction1() {
myFunction(globalVar);
}
You can try like this, a global variable is something which is declared in a page, outsite of a javascript function ,and is fully accessible any where in that page. So for that, declare the variable outside of the function and call it from anywhere.like
<script>var globalVar = "global Variable";
function(){
////
}
</script>
call variable as,
<script>function myFunction(){
console.log(globalVar );
}</script>
Hope this will help.Thanks.