I am using JS to pass data to Python. First, when the HTML is loaded I want to collect the values and this works, the issue is when the value changes, it doesn't change.
Please excuse me, I am quite new to JS. Here is my working code:
<input type="date" id="start-date" name="start-date" value="2019-10-10"/>
<label for="date">to</label>
<input type="date" id="end-date" name="end-date" value="2020-05-10"/>
<script>
document.onreadystatechange = function () {
var start_date = document.getElementById("start-date").value;
var end_date = document.getElementById("end-date").value;
$.ajax({
url: "/dates",
type: "GET",
data: {
start_date: start_date,
end_date: end_date,
},
});
};
</script>
document.onreadystatechange does not make any sense.
You need a change event
Here I delegate from document.
window.addEventListener("DOMContentLoaded", function() { // only needed if the script is not after the date elements
document.addEventListener("change",function(e) { // this can be narrowed to a closer container like a form
const tgt = e.target;
if (!tgt.matches("[type=date]") return; // not a date change
let start_date = document.getElementById("start-date").value;
let end_date = document.getElementById("end-date").value;
$.get("/dates", {start_date, end_date },function(data) {
console.log(data); // returned from server
});
});
});
Alternative using the same event handler for both dates
window.addEventListener("DOMContentLoaded", function() { // only needed if the script is not after the date elements
const startDateField = document.getElementById("start-date");
const endDateField = document.getElementById("end-date");
const dateChange = e => {
let start_date = startDateField.value;
let end_date = endDateField.value;
$.get("/dates", {start_date, end_date },function(data) {
console.log(data); // returned from server
});
};
startDateField.addEventListener("change",dateChange);
endDateField.addEventListener("change",dateChange);
});