I'm having trouble implementing a feature that involves selecting a region from a dropdown list and requesting rainfall data to display in a Google Chart.
Unfortunately, I've encountered some issues with it.
Could you please help me identify what the problem might be?
Apologies for the messy code - I'm still new to JavaScript. I've added comments to make it easier to understand.
Thank you :)
You can find the demo here.
Here is the HTML -
<!-- Some text -->
<div class="text">
Pick a region from the list below to view its annual rainfall.
</div>
<!-- Dropdown list of regions -->
<div>
<select class="region">
<option selected="selected" disabled>Select a region</option>
<option>Andaman & Nicobar Islands</option>
<option>Arunachal Pradesh</option>
<option>Assam, Meghalaya</option>
...
</select>
</div>
<!-- Button to request data -->
<div>
<button type="button">Get data!</button>
</div>
<!-- Container for the chart -->
<div id="chart">
</div>
Here is the JavaScript -
// Get the selected region
var region = jQuery(".region").find(":selected").text();
// Create button variable
var button = jQuery("button");
// Detect changes in selected region
jQuery(".region").change(function() {
region = jQuery(".region").find(":selected").text();
});
// Handle button click to load Google Charts
button.click(function() {
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
// Function to draw the chart
function drawChart() {
var query;
// Check which region is selected and define the corresponding query
if (region == "Andaman & Nicobar Islands") {
query = new google.visualization.Query("query-url");
} else if (region == "Arunachal Pradesh") {
query = new google.visualization.Query("query-url");
} else if (region == "Assam, Meghalaya") {
query = new google.visualization.Query("query-url");
...
// Send the query and handle response
query.send(handleQueryResponse);
}
// Function to handle query response and render the chart
function handleQueryResponse(response) {
var data = response.getDataTable();
var options = {...};
...
var chart = new google.visualization.BarChart(document.getElementById("chart"));
chart.draw(view, options);
window.addEventListener('resize', function() {
chart.draw(view, options);
}, false);
}
});