简体   繁体   中英

chart title from <input type='text'> with jquery

I'm new with jquery. I have a html and jquery that plots a line chart from a csv. I would like to write a text in a textbox and append it to my chart.

Any help is appreciated :)

<div class="optionGroup"><label for="chart_title">Title</label><input type="text" name="chart_title" value="" id="chart_title"></div> 



var chart = new google.visualization.LineChart(document.getElementById('chart'));

//this is my attempt 
var titlus = +$('#chart_title').keyup(function(){ 
 var value = $( this ).val();
 $( 'chart'  ).text( value );
 })

var options = {
 title: titlus,//<--it should go here
 hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
 vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
 legend: 'none'
};

chart.draw(view, options); 

You need to render the graph in the beginning, if you want to change the graph title in real time you should draw the graph again when a key is pressed. In order to do this a callback function for load must be added because the rendering/API is asynchronous. As a recommendation, it is a not a good practice rendering the graph any time a key is pressed, it is better to create a button to submit the title or detecting when the return key is pressed. This is a working example of what you asked:

<!doctype html>
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance'
        };
        var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
        chart.draw(data, options);
        document.getElementById("chart_title").onkeyup = function() {
           options.title = this.value;
           chart.draw(data, options);
        }
      }
    </script>
  </head>
  <body>
    <div>
        Title: <input type="text" name="chart_title" value="" id="chart_title">
    </div>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM