I'm a newbie in javascript. As the title says, I'm trying to call javascript function from html generated by another javascript function. Following is a simple version of this code:
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
function myFunction1()
{
var html_text = "<HTML><BODY><FORM><INPUT type=\"button\" onClick=
\"myFunction2()\" value=\"function2\" /></FORM></BODY></HTML>";
document.write(html_text);
document.close();
}
function myFunction2()
{
alert("function2 called!");
}
</SCRIPT>
</HEAD>
<BODY>
<FORM><INPUT type="button" onClick="myFunction1()" value="function1"
/></FORM>
</BODY>
</HTML>
When I run firebug, I got an error saying "myFunction2 is not defined". I guess I have to put myFunction2 in html code generated by myFunction1. So I changed my code like this:
<HTML>
<HEAD>
<SCRIPT language="JavaScript">
function myFunction1()
{
var html_text = "<HTML><HEAD><SCRIPT language=\"JavaScript
\">function myFunction2(){alert(\"function2 called!\");}
</SCRIPT></HEAD><BODY><FORM><INPUT type=\"button\" onClick=\"myFunction2()\"
value=\"function2\" /></FORM></BODY></HTML>";
document.write(html_text);
document.close();
}
/* function myFunction2()
{
alert("function2 called!");
} */
</SCRIPT>
</HEAD>
<BODY>
<FORM><INPUT type="button" onClick="myFunction1()" value="function1"
/></FORM>
</BODY>
</HTML>
However, after this change I got some messy result and the firebug says "unterminated string literal for var html_text=...". Any suggestions? Also, my actual myFunction2 is really big, if I have to insert it into the html generated by myFunction1, is there a good way to put it in? Also, the instructor doesn't want us to use a separate file. Thanks!
</script>
in a string in javascript. – jbabey Sep 27 '12 at 17:22