Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined value javascript

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);
}
like image 219
Bojana Cubranovic Avatar asked Jun 11 '26 09:06

Bojana Cubranovic


2 Answers

The problem

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.

like image 116
Filip Roséen - refp Avatar answered Jun 19 '26 16:06

Filip Roséen - refp


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

like image 35
Tyler McGinnis Avatar answered Jun 19 '26 17:06

Tyler McGinnis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!