javascript - How to visualize data with chart.js properly? -
i making program, data array , make array. array needs visualize via chart.js in line chart, goes wrong there... code:
<html> <head> <title>visualize data beautifully using js charts</title> <link href="css/style.css" media="screen" rel="stylesheet"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/1.0.2/chart.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script> </head> <body> <center> <form> <p>first value:</p> <input type="text" name="firstname" id="first"> <br/>last value: <br/> <input type="text" name="secondname" id="second"> <br/> <input type="submit" id="btnsubmit" value="submit" /> </form> </center> <script> $(document).ready(function() { $('#btnsubmit').on("click", function() { var array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]; var newarray = []; var firstval = $('#first').val(); var lastval = $('#second').val(); (var = 0; < array.length; i++) { if (array[i] >= firstval && array[i] <= lastval) { newarray.push(array[i]); } } var ctx = $("#mychart").get(0).getcontext("2d"); (var = 0; < newarray.length; i++) { var data = { labels: [1, 5, 8, 4, 5, 6, 7, 8, 9, 10], datasets: [ { fillcolor: "rgba(151,187,205,0.5)", strokecolor: "rgba(151,187,205,1)", pointcolor: "rgba(151,187,205,1)", pointstrokecolor: "#fff", data: newarray[i] } ] } } var mynewchart = new chart(ctx).line(data); }); }) </script> <div> <section> <article> <canvas id="mychart" width="400" height="400"> </canvas> </article> </section> </div> </body> </html>
can please me that, because have no idea might mistake in code, new jquery , chart.js.
your button has type="submit"
. submits form when click refreshing it. change type="button"
<input type="button" id="btnsubmit" value="submit" />
the data
property dataset
should array. can take out outer loop , directly plug in newarray
var ctx = $("#mychart").get(0).getcontext("2d"); var data = { labels: [1, 5, 8, 4, 5, 6, 7, 8, 9, 10], datasets: [ { fillcolor: "rgba(151,187,205,0.5)", strokecolor: "rgba(151,187,205,1)", pointcolor: "rgba(151,187,205,1)", pointstrokecolor: "#fff", data: newarray } ] }
with these 2 changes, putting in first , last value (say 20 , 60) plot chart.
however, if want data align original indices (and not pushed left), should inserting null values in first loop
if (array[i] >= firstval && array[i] <= lastval) { newarray.push(array[i]); // add new array } else { newarray.push(null); }
Comments
Post a Comment