Click to See Complete Forum and Search --> : creating a JS function in a DIV


kimoo
April 30th, 2008, 12:42 PM
<script type="text/javascript">
function xx(){

document.getElementById('x').innerHTML="<script>function t(){alert('here');}</script>";

}
</script>

<a onClick="xx();">Send Function</a>

<a onClick="t();">test Function</a>

<div id="x"></div>



In the above function i am trying to send a <script> containing a function t();

when i click on the Anchor tag "Send Function".

Then upon clicking the Test function Anchor tag it is supposed to run the t() function which it DOES NOT can anybody tell me the reason..

regards,
kimoo

PeejAvery
May 1st, 2008, 12:55 PM
can anybody tell me the reason.
Yes. It is because you can't create function dynamically in that manner. The browser will see the <script> inside of the quotes and automatically begin another scripting section. This will cause the browser to throw an unterminated string error.

mrjeffs
May 6th, 2008, 12:21 PM
This mimics the functionality you are asking for in this specific instance, although it does not dynamically write a function to an element -

<script type="text/javascript">
var sendFunction = false;
function t() {
if (sendFunction == true) {
alert('here');
}
}
function xx(){
sendFunction = true;
}
</script>

<a onClick="xx();">Send Function</a>

<a onClick="t();">test Function</a>

<div id="x"></div>