Search code examples
jqueryfunctionruntimeupdatingscript-tag

Trying to update the function in script tag using jQuery


I am creating a debugger utility to help me out in debugging without the to follow cumbersome process of redeploying and going to all the way to the page to test it. so I have created the below functions which are called by various buttons.

     function updateTestCode()
    {
        $("script[for='testing']").html('');
        alert('Adding function ' + $('#_testArea').val());
        $("script[for='testing']").append($('#_testArea').val());



    }

function checkCode()
{
    alert('Calling Function ');
    try{
        validateFields();
    }catch(err)
    {
        form.showDebugMsg("Error When Running Script " + err);
    }
}

function generateScriptCode()
{
    $('#_testArea').val($("script[for='testing']").html());
}

Now all I wanted to do is to allow me to update the value of the function below and use it without the need for redeployment.

<script type="text/javascript" for='testing'>
function validateFields()
{
    alert('Hello World');

}</script>

Now the problem is that Firefox is able to update the code (IE throws error) and retrieve it. But when I try to click and execute the script it still show result of the old function.

Any Ideas what I might be doing wrong???


Solution

  • This is happening because you're using the same script tag and changing the inner text. You have to add a new script tag.

    scriptContent = "... function ...";
    
    // delete old tag
    $("#testScript").remove();
    
    // add a new one
    $("<script id='testScript'/>").text(scriptContent).appendTo("head");
    

    Also, you cannot use append() to add text to an element like you're doing on your updateTestCode() function. You have to use the text().

    // use text(), not append()
    $("script[for='testing']").text($('#_testArea').val());
    

    Here an working example: http://jsfiddle.net/MtY3h/