Based on in this response of @Bacco, you can use the onchange
attribute of the field to do this verification .
function funcao(data){
var dtInicio = document.getElementById('data1');
var dtFim = document.getElementById('data2');
if(dtInicio.value.length > 0 && dtFim.value.length > 0){
dtInicio = dtInicio.value.split("/");
dtFim = dtFim.value.split("/")
data1 = new Date(dtInicio[2] + "/" + dtInicio[1] + "/" + dtInicio[0]);
data2 = new Date(dtFim[2] + "/" + dtFim[1] + "/" + dtFim[0]);
var total = dateDiferencaEmDias(data1, data2);
if(isNaN(total)){
alert("Data inserida invalida!");
}else{
alert("total de: " + total + " dias");
}
}
}
function dateDiferencaEmDias(a, b) {
var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / ( 1000 * 60 * 60 * 24) );
}
Digite uma data de inicio: <input type='text' id='data1' onchange='funcao(this.value)'><br/>
Digite outra data final: <input type='text' id='data2' onchange='funcao(this.value)'>
Obs : I am not an adept at using Jquery
when there is no need for it ...
Update responding to the questioner's question
You can use the date field with no problem, and only change type='text'
to type='date'
.
It does not matter where you call the code JavaScript
, always remembering that you must abide by the HTML
writing standards.
An example of the complete code for you to get an idea of how you can mount:
<html>
<head>
<script>
function funcao(data){
var dtInicio = document.getElementById('data1');
var dtFim = document.getElementById('data2');
if(dtInicio.value.length > 0 && dtFim.value.length > 0){
dtInicio = dtInicio.value.split("/");
dtFim = dtFim.value.split("/")
data1 = new Date(dtInicio[2] + "/" + dtInicio[1] + "/" + dtInicio[0]);
data2 = new Date(dtFim[2] + "/" + dtFim[1] + "/" + dtFim[0]);
var total = dateDiferencaEmDias(data1, data2);
if(isNaN(total)){
alert("Data inserida invalida!");
}else{
alert("total de: " + total + " dias");
}
}
}
function dateDiferencaEmDias(a, b) {
var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / ( 1000 * 60 * 60 * 24) );
}
</script>
</head>
<body>
<form>
Digite uma data de inicio: <input type='date' id='data1' onchange='funcao(this.value)'><br/>
Digite outra data final: <input type='date' id='data2' onchange='funcao(this.value)'>
</form>
</body>
</html>