I am working on an HTML page that uses Morris.js to create charts. I added calendar widgets to allow the user to choose a start and an end date, and a button to update the data. I realized it would be convenient if I automatically set the dates to "today" so the charts already have data when first loaded. Everything is working fine: the dates are set to today, the queries return valid JSON, and the charts display the correct data. However, the <input>
fields are not updated and I can't figure out why. Also worth noting, after pressing the button on "empty" fields, the dates are correctly set and DO appear in the inputs afterwards. Here is the relevant code:
<script> // inside head tag
function updateCharts() {
startDate = document.getElementById("startDate").value;
endDate = document.getElementById("endDate").value;
scale = document.getElementById("scale").value;
console.log("before " + startDate);
if (startDate == "") {
console.log("empty start");
var today = new Date;
startDate = today.getFullYear() + "-" +
(today.getMonth() + 1) + "-" + // getMonth in range [0,11]
5;//today.getDate();
document.getElementById("startDate").value = startDate;
console.log("input " + document.getElementById("startDate").value);
}
if (endDate == "") {
console.log("empty end");
endDate = startDate;
document.getElementById("endDate").value = endDate;
console.log("output " + document.getElementById("endDate").value);
}
console.log("after " + startDate + " " + endDate);
var charts = ['providers', 'variance', 'cities', 'convertions', 'unique_ids'];
var len = charts.length;
for (var i = 0; i < len; i++) {
var chartType = charts[i]
chart(chartType, startDate, endDate, scale);
}
}
</script>
Here are the input tags:
<div id="dates" class="row">
<p>From: <input type="text" id="startDate" />
To: <input type="text" id="endDate" />
<select id="scale">
<option value="0">Hour</option>
<option value="1">Day</option>
<option value="2">Month</option>
</select>
<button value="Show" onclick="updateCharts()">Show</button>
</p>
</div>
And my script at the end of the body to call the function:
<script>
window.onload = updateCharts();
</script>
</body>
The console output after the load, before pressing the button:
before
index.html (line 41)
empty start
index.html (line 43)
input 2015-11-5
index.html (line 49)
empty end
index.html (line 52)
output 2015-11-5
index.html (line 55)
after 2015-11-5 2015-11-5
So as you can see the value is (correctly?) set and retrieved by Javascript after the conditionals, but it is not shown in the browser.