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);
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With