javascriptjqueryhtmlgoogle-visualizationgoogle-pie-chart

Dynamic create div


I was trying to use Google Chart pie and show many Pies in the same page. So, I need to create dynamic div. Btw I use ASP.NET

Here is my javascript

 <script type="text/javascript">

    $(document).ready(function () {

        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            url: 'printG.aspx/GetData',
            data: '{}',
            success:
                function (response) {
                    drawVisualization(response.d);
                }
        });
    })

    function drawVisualization(dataValues) {
        var data = new google.visualization.DataTable();
        var output = document.getElementById('output');
        var ele = document.createElement("div");
        ele.setAttribute("style", "width: 600px;");
        ele.setAttribute("style", "visualization");
        ele.setAttribute("id", "width: 600px;");
        output.appendChild(ele);

        //data.addColumn('string', 'title');
        data.addColumn('string', 'Anstitle');
        data.addColumn('number', 'chooseP');

        for (var i = 0; i < dataValues.length; i++) {
            data.addRow([dataValues[i].ColumnName, dataValues[i].Value]  );
            console.log(dataValues[i].ColumnName +" "+ dataValues[i].Value+" "+ i);
        }

        new google.visualization.PieChart(document.getElementById('visualization')).
            draw(data, { title: dataValues[0].QuestionName });


    } 

</script>

Html

<div id="output" class="out">

However, it show an error :

Uncaught Error: Container is not defined

It looks like I didn't create a container where google pie appended value.

How to fix it?


Solution

  • Here you are referring to your new dynamic div using an ID of "visualization":

    new google.visualization.PieChart(document.getElementById('visualization')).
            draw(data, { title: dataValues[0].QuestionName });
    

    But you are setting the ID to "width: 600px;" here:

        ele.setAttribute("style", "width: 600px;");
        ele.setAttribute("style", "visualization");
        ele.setAttribute("id", "width: 600px;");
    

    Perhaps think about those attributes and what you really want them to be set to.