Take the tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to add html variables : "<script>var var1 = new CalendarPopup();</script>" according to a number that the user chooses. At the moment I have an ajax setup that is suppose to change my tag to add the variables by changing the inner html like so :

<div id="calVar">
    <script>
        var cal1 = new CalendarPopup();
        var cal2 = new CalendarPopup();
    </script>
</div>



        function addRespDropDownAjax(currentNumberOfDropDown)
    {

        //Prepare a new ajaxRequest.
        if (window.XMLHttpRequest) 
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        //Ajax receiving the response in this function
        xmlhttp.onreadystatechange = function() 
        {
            //state 4 is response ready.
            //Status 200 is page found.
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {


                document.getElementById('calVar').innerHTML = '<script>var cal3 = new CalendarPopup();</script>';
                    alert(document.getElementById('calVar').innerHTML);

            }
        };

        //Send the Ajax request.
        xmlhttp.open('GET','mainServlet?command=ajax.AddRespDropDown&NUMBER_OF_DROP_DOWN=' + currentNumberOfDropDown, true);
        xmlhttp.send();

    }

The last alert :document.getElementById('calVar').innerHTML return nothing and my varaibles are not created. any ideas?

Thanks alot!!

share|improve this question
2  
That is a JavaScript variable, not an HTML variable. Why not just create the JS in the script? –  zzzzBov Feb 20 at 14:52
1  
You're really overthinking this. –  Juhana Feb 20 at 14:53
 
window.cal3 = new CalendarPopup();. Done. –  Brad Christie Feb 20 at 14:55
 
Are you getting the 200 response? Did you try debugging (breakpoints)? Is the addRespDropDownAjax called after the div? Why not assign cal3 directly (as previous commenters noted). –  Friso Feb 20 at 14:58
 
@Friso I can't debug it really. I am using eclipse and I can't install any other programm because it is not my computer. –  Benchy Feb 20 at 15:00
show 1 more comment

1 Answer

up vote 1 down vote accepted

HTML doesn't have variables, and any that are defined in a <script> without deeper nested scope can be simple defined off the window object.

Instead of trying to insert HTML, just use:

window.cal3 = new CalendarPopup();

then any other script can access this variable now or later.

share|improve this answer
 
Thanks it is working like a charm!! –  Benchy Feb 20 at 15:06
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.