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.
Fiddle
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");