I have 3 inputs and from where by click in a button get those input value and create a Google Visualization dynamic Pie Chart depend on those value . I have made like this code below , but did not getting expecting result
HTML
<input type="text" name="BigHalo" id="BigHalo">
<input type="text" name="MediumHalo" id="MediumHalo">
<input type="text" name="SmallHalo" id="SmallHalo">
<button type="button" onclick="onclickChartValur()" >CLICK HERE</button>
<div id="donutchart" style="width:380px; height:380px;"></div>
SCRIPT CODE
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart(BigHalo,MediumHalo,SmallHalo) {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['Big Halo', BigHalo],
['Medium Halo', MediumHalo],
['Small Halo',SmallHalo]
]);
var options = {
legend: 'none',
pieSliceText: 'label',
title: '',
pieStartAngle: 100,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
function onclickChartValur() {
var BigHalo = $("#BigHalo").val();
var MediumHalo = $("#MediumHalo").val();
var SmallHalo = $("#SmallHalo").val();
drawChart(BigHalo,MediumHalo,SmallHalo);
}
</script>
ERROR RESULT ::
EXPECTING RESULT
It is Solved! I made it . Here I am sharing this technique.
HTML
<input type="text" name="BigHalo" id="BigHalo">
<input type="text" name="MediumHalo" id="MediumHalo">
<input type="text" name="SmallHalo" id="SmallHalo">
<button type="button" onclick="onclickChartValur()" >CLICK HERE</button>
<div id="donutchart" style="width:380px; height:380px;"></div>
Script
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function drawChart(BigHalo,MediumHalo,SmallHalo) {
var data = google.visualization.arrayToDataTable([
['Language', 'Speakers (in millions)'],
['Big Halo', parseInt(BigHalo)],
['Medium Halo', parseInt(MediumHalo)],
['Small Halo', parseInt(SmallHalo)]
]);
var options = {
legend: 'none',
title: '',
pieStartAngle: 100,
};
var chart = new google.visualization.PieChart(document.getElementById('donutchart'));
chart.draw(data, options);
}
function ontypeChartValur() {
var BigHalo = $("#BigHalo").val();
var MediumHalo = $("#MediumHalo").val();
var SmallHalo = $("#SmallHalo").val();
drawChart(BigHalo,MediumHalo,SmallHalo);
}
</script>
And OnClick event this cart will be generate easily ! Also we can make it with onKeyup / onKeydown event also.
NOTE : parseInt is used here because of convert string to number.
Related
The weights that have been calculated in program needs to be displayed in a graph. I have added into the code an example taken from here: https://developers.google.com/chart/interactive/docs/gallery/linechart#creating-material-line-charts
Obviously the variable data needs to be replaced by weight, so the existing data (line 17 to 31) can be discarded. The latest version of the code is attached
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['line'] }); // load the visualisation API and corechart package
google.charts.setOnLoadCallback(drawChart); // set a callback to run when the Google Visualization API is loaded
// Callback that creates and populates a data table, instantiates the chart, passes in the data and draws it.
function drawChart() {
// Create the data table for the symbol in question.
var data = new google.visualization.DataTable();
data.addColumn('number', 'k');
data.addColumn('number', 'lambda');
data.addRows([
[-0.050, 0.00952],
[-0.040, 0.00952],
[-0.030, 0.01904],
[-0.025, 0.03809],
[-0.020, 0.02857],
[-0.015, 0.04761],
[-0.010, 0.02857],
[-0.005, 0.18095],
[0.000, 0.21904],
[0.005, 0.16190],
[0.010, 0.12380],
[0.015, 0.05714],
[0.020, 0.03809],
[0.030, 0.02857],
[0.080, 0.00952]
]);
var chart = new google.charts.Line(document.getElementById('#chart_weights'));
chart.draw(data, { height: 288, width: 550, lineWidth: 1 });
}
</script>
</head>
<body>
<table>
<tr><td>k: </td><td><input id="k" type="number" value="2.2" min="0" max="10" step="0.1" /></td></tr>
<tr><td>lambda: </td><td><input id="lambda" type="number" value="7.6" min="0" max="10" step="0.1" /></td></tr>
</table>
<p id="message"> </p>
<script type="text/javascript">
UpdateValues();
document.getElementById("k").addEventListener("click", function() {
UpdateValues();
});
document.getElementById("lambda").addEventListener("click", function() {
UpdateValues();
});
function UpdateValues() {
var weight = [];
var k = document.getElementById("k").value;
var lambda = document.getElementById("lambda").value;
for (var x = 0.1; x < 20; x++) {
weight.push([x, k * Math.pow(x/lambda, k-1) * Math.exp(-Math.pow(x/lambda, k)) / lambda]);
document.getElementById("message").innerHTML = weight;
}
}
</script>
<div id="chart_weights"></div>
</body>
</html>
I don't know why these graphs are not beiNg displayed..
THanks in advance to helping hands
Please, check this example
So, The main problem was that Container is not defined.
In your code you write document.getElementById('#chart_weights') but you should write document.getElementById('chart_weights') without #.
I have created a form and trying to display submitted values in the google chart. I have tried to create wrapper for drawChart() and want to load drawChart() after submit button is clicked. But, drawChart() function gets called onload. What is the problem with my code?
HTML-
<form method= "post" action = "#" id="formValue">
<label><input type="number" value="1" id="ip1"/>inpu1</label>
<label><input type="number" value="2" id="ip2"/> input2</label>
<input type="submit" value="Add" onclick="initializer()"/>
</form>
JS-
<script>
var ip1, ip2;
var str = "hello";
var str2 = "hello2";
function initializer(){
ip1 = document.getElementById("ip1").value;
ip2 = document.getElementById("ip2").value;
drawChart();
}
google.charts.setOnLoadCallback(initializer);
google.charts.load('current', {'packages':['corechart']});
function drawChart() {
var x2= [
[
str,
ip1
],
[
str2,
ip2
]
];
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(x2);
var options = {'title':'How Much Pizza I Ate Last Night',
'width':500,
'height':600};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
remove this...
google.charts.setOnLoadCallback(initializer);
it runs initializer when...
google.charts.load('current', {'packages':['corechart']});
is finished.
My task is to report a graph by accessing sqlite3 database table values. So i created database in python and i used javascript to report a graph.In python, i fetched all values from database and stored in list. Now, my problem is i dono how to access python list values from javascript. please help me..
import sqlite3
list = []
conn = sqlite3.connect('persistentautomation.db')
cursor = conn.execute("SELECT date, gb from memoryused")
for row in cursor:
print "date :", row[0]
print "gb :", row[1]
list.append([row[0],row[1]])
def memory():
return list
req = memory();
print req #This is the list which i created
memory();
ff = open('chart.html','w')
msg='''
<html>
<head>
<script type="text/javascript"
src=\'https://www.google.com/jsapi?autoload={
"modules":[{
"name":"visualization",
"version":"1",
"packages":["corechart"]
}]
}\'></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([ .
#i want to pass that list variable here...help please..
]);
var options = {
title: "PERSISTENT AUTOMATION MEMORY USAGE REPORT",
curveType: "function",
legend: { position: "bottom" }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>'''
ff.write(msg)
ff.close()
import sqlite3
from string import Template
conn = sqlite3.connect('persistentautomation.db')
cursor = conn.execute("SELECT date, gb from memoryused")
results = []
for row in cursor:
results.append({'date': row[0], 'gb': row[1]})
print "date :", row[0]
print "gb :", row[1]
template = '''
<html>
<head>
<script type="text/javascript"
src=\'https://www.google.com/jsapi?autoload={
"modules":[{
"name":"visualization",
"version":"1",
"packages":["corechart"]
}]
}\'></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Memory", "Usage (GB)"],
$res
]);
var options = {
title: "PERSISTENT AUTOMATION MEMORY USAGE REPORT",
curveType: "function",
legend: { position: "bottom" }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>'''
with open('chart.html', 'w') as html:
data = ','.join(['["{date}", {gb}]'.format(**r) for r in results])
html.write(Template(template).substitute(res=data))
You should iterate over list and concatenate items to the result string.
items = ['apple', 'grape']
html_string = '''
<html> <body> <h1> My list </h1> <ul>{list}</ul> </body> </html>
'''
my_list = ''.join(['<li>{}</li>'.format(i) for i items])
html_string = html_string.format(list=my_list)
with open('test.html', 'w') as html:
html.write(html_string)
This is a very easy way to achieve the above task.
import ast
memory_used = "/Users/Shared/MemoryUsed.log"
memory_used = []
with open(memory_used) as f:
for line in f:
linesplit = line.split()
date = linesplit[1]
gbsplit = linesplit[2]
gb = ast.literal_eval(gbsplit[0])
memory_used.append([date,gb])
print memory_used #This is the list
ff = open('chart_new_try.html','w')
html1="""<html>
<head>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'MemoryUsed'],"""
html2 = """ ]);
var options = {
title: 'GRAPH REPORT',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>"""
msg = html1 + memory_used + html2
ff.write(msg)
ff.close()
I would like to display my retrieved data points from my server side text file
on a google graph. During research i can now retrieve the data from my temps.txt
file using $.get().
I just started learning javascript , so this may be something obvious that i missed.
I can also display a sample google graph with some example datapoints.
How can i put the two together? , below i have both source files
from my attempts so far.
Getting the Datapoints:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 16px;
font-family: Arial;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
var times = [];
$.get('temps.txt', function(data) {
times = data.split("\n");
var html = [];
for (var i in times) {
html.push(times[i] + '<br/>');
}
html.push( times[0] * 3 );
$('body').append(html.join(''));
});
</script>
</html>
Showing the GRAPH:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Hours', 'Temperature'],
['18:00', 20.7],
['19:00', 21],
['20:00', 22.3],
['20:30', 22.5],
['21:00', 22.0],
['22:00', 21.6]
]);
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 700px; height: 400px;"></div>
</body>
</html>
Temps.txt file is a simple text file with one measured value every hour
the first line is 00:00 hrs the 2nd line 01:00 hrs and so on see below:
15.3
16.4
16.7
18.8
... etc
Well, would be something like this:
function drawChart() {
$.get('temps.txt', function(txt) {
vals = txt.split("\n");
var hour= 0;
var dataArr=[['Hours', 'Temperature']]
for(var i = 0; i < vals.length;i++){ // build data array
//add the hour in 'hh:00' format and the temperature value
dataArr.push([('0'+hour).substring(-2)+':00', parseFloat(vals[i])]);
hour+=1;
}
var data = google.visualization.arrayToDataTable(dataArr)
var options = {
title: 'Temperatuur Grafiek',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
Good day.
I'm trying to add Google Places Autocomplete on dynamically created inputs using code below:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var _autoComplCounter = 0;
function assignAutoCompl(_id)
{
var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id));
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
//processing code
});
}
function CreateElem()
{
var _id = "AutoCompl" + _autoComplCounter;
_autoComplCounter++;
var container = document.getElementById('AutoComplInputs');
container.innerHTML += "<br>" + _id;
var _elem_for_upd = document.createElement("input");
_elem_for_upd.type = "text";
_elem_for_upd.id = _id;
container.appendChild(_elem_for_upd);
assignAutoCompl(_id);
}
</script>
</head>
<body>
<div id="AutoComplInputs"></div>
<input type='button' value='Add' onclick='CreateElem();'>
</body>
</html>
But when I press on button, autocomplete works only on last input, and all prevoius become broken. I think that it can be connected to dynamic creation of inputs, as the code below works fine:
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var _autoComplCounter = 0;
function assignAutoCompl(_id)
{
document.getElementById(_id).hidden = false;
var _autocomplete = new google.maps.places.Autocomplete(document.getElementById(_id));
_autocomplete.setTypes(['geocode']);
google.maps.event.addListener(_autocomplete, 'place_changed', function()
{
//processing code
});
}
function CreateElem()
{
assignAutoCompl("AutoCompl0");
assignAutoCompl("AutoCompl1");
}
</script>
</head>
<body>
<div id="AutoComplInputs">
<input id="AutoCompl0" type="text" hidden>
<input id="AutoCompl1" type="text" hidden>
</div>
<input type='button' value='Add' onclick='CreateElem();'>
</body>
</html>
I don't understand what I'm doing wrong ...
Don't use innerHTML to add content to container, you will lose all handlers bound to existing elements.
Use appendChild instead:
container.appendChild(document.createElement('br'));
container.appendChild(document.createTextNode(_id));