I am trying to create a function dynamically everytime a user supplies a JSON file. The following function is called at onSubmit event of the form.
I dont see this code working. While debugging, I saw that the extra element appears in the HEAD section but as soon as the function call gets over, it disappears.
However, if I call the function createType() explicitly in JS file, it works. But my requirement is that the function createType should be called only on the button click and should create a function dynamically.
function createType() {
var jsonString = document.getElementById("json").value;
var obj = JSON.parse(jsonString)
var script = document.createElement("script");
script.innerHTML = "function Friend(){ ";
for (var i = 0; i < obj.fields.length; i++) {
if (obj.fields[i].name != "") {
alert(obj.fields[i].name);
script.innerHTML += "var " + obj.fields[i].name + ";" +
"this.get=function(){ alert('test');}";
}
}
script.innerHTML += "}";
document.head.appendChild(script);
}
var firstFriend = new Friend();
firstFriend.get(); // should trigger an alert box.
The last two lines throw an error because the new script tag which contains the function 'Friend' is not found anywhere.
I want the appended script to stay in HEAD/BODY even if the createType() was called from a button click event.