0

Here I have to create highchart dynamically based on dynamic id which generates from index++. when I click submit1 button chart will create dynamically.Again when I click download button an array will be showing in console based on created id.When I console it its showing as the array like [$('#chart-0'),$('#chart-1')] which I created dynamically,same time when I hardcode the samearray and console it its showing as created chart [r.fn.init(1), r.fn.init(1)],here what I need is when I console ('console.log(strreplace)') the created array also should display as chart same as like harcoded (console.log(elements)) value.Here is code below

html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 <script src="https://code.highcharts.com/highcharts.js"></script>
  <input type="button" id="download"  value="download" /> click to console
  <div><button id="button1" class="button1">submit1</button></div>

script

$(document).ready(function() {
    var index = 0;
    var id = [];
  $('#button1').on('click', function() {
    $('body').append($("<div id='chart-" + index + "'></div>"));

    Highcharts.chart('chart-' + index, {
        series: [{
            data: [1, 2, 3]
        }]
    });
    var temp="$('#chart-"+index+"')";
        id.push(temp);
        console.log('chart' + index);

    index++;
});
 $('#download').on('click', function() {
    var string = JSON.stringify(id);
var strreplace = string.replace (/"/g,'');
 console.log(strreplace); 
 var elements = [$('#chart-0'),$('#chart-1')];
 console.log(elements); 

});
}); 
carreankush
  • 621
  • 2
  • 9
  • 32

1 Answers1

0

JavaScript does not work that way, after replacing "" the code inside will not be called. To acheive the wanted result, you would have to use eval, but it is strongly not recommended: what does eval do and why its evil?

$('#download').on('click', function() {
    console.log(eval(id[0]));
    var elements = [$('#chart-0'), $('#chart-1')];
});

Live demo: http://jsfiddle.net/BlackLabel/mw21utbk/

ppotaczek
  • 36,341
  • 2
  • 14
  • 24
  • Thanks for your answer, here its hardcoded to 0 (eval(id[0])) ,so if I click submit1 button twice or multiple times and then click download button it will give the output for only first chart.It should give the output for all the created chart.Can you please help me on it – carreankush Nov 05 '18 at 17:19
  • Hi carreankush, You have to use `eval` to all elements in array: http://jsfiddle.net/BlackLabel/mq51n9hy/ – ppotaczek Nov 06 '18 at 11:30