Reputation: 39
I'm trying to run a javascript function with values but gets the answer val is undefined.
I want to append this value
Function run
myufunc("test msg");
code
function myufunc(val){
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'alert(val);';
document.body.appendChild(script);
}
Upvotes: 2
Views: 87
Reputation: 64526
The issue is val
is only available in the myufunc
scope, and when your script is appended, it is executed in the global scope, not your function scope. Thus, val
is not defined in the global scope.
A solution is to create a global variable and set its value to val
, then use the global in the alert. Using this way, there is no need to concatenate the variable into the string, and so you don't have the problem of the variable containing quotes and breaking the string.
function myufunc(val){
myValue = val; // create global
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'alert(myValue);'; // use the global
document.body.appendChild(script);
}
The following will all work:
myufunc('test');
myufunc('tes"t');
myufunc("tes't");
Upvotes: 0
Reputation: 5358
First, "int" is a reserved word in Javascript-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words
Second, you are using "val" as if it were a string, not a variable.
init("test msg");
function init(val){
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'alert('+val+');';
document.body.appendChild(script);
}
Upvotes: 1
Reputation: 63797
The problem is that your created script-tag will contain alert(val)
, but val
hasn't been initialized; it does exists inside your function - but the newly created script-element have no idea what val
you are referring to.
You probably want the element to end up containing alert("test msg");
:
function f(val){
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'alert("' + val + '");';
document.body.appendChild(script);
}
f ("test msg"); // will create a <script> containing `alert("test msg");`
Note: since we are manually wrapping the contents of val
with double-quotes, be careful so that the passed in value itself doesn't contain a double-quote "
; this will break the "generated" code.
Upvotes: 7
Reputation: 35276
int is a reserved word in JavaScript, so definitely don't use it. That's most likely the reason your code isn't working properly.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words
Upvotes: 1