Reputation: 115
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.
Upvotes: 0
Views: 154
Reputation: 943207
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.
You are running the script, then the form is submitting which causes the page to be reloaded. The script hasn't run on the new page so the changes no longer exist.
You need to call .preventDefault()
on the event object to stop the form submission completing.
If you need the form to submit then you also need to replace the regular submission with Ajax or change your approach and trigger the JS based on the data submitted when the page is loaded.
Upvotes: 2