Basing myself in that reply from @Bacco, you can use the attribute onchange
field to make this check.
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’m not a fan of the use of Jquery
when there is no need for it...
Update Answering Question Author’s Question
You can use the date field without any problem, and just change the type='text'
for type='date'
.
No matter where you call the code JavaScript
, always remembering that you must respect the writing patterns HTML
.
An example of the full code for you to get an idea of how you can assemble:
<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>
This is relatively simple... when should Alert? appear when you focus on input? or when you click on Ubmit before submitting the form? and what values do you want in response? days, hours?
– Sergio
The title should be more enlightening, in my opinion
– Wallace Maxters
Sergio, I wish that when I focusout, there would be an Alert of my variable difference.
– Gonçalo
In which format the dates are inserted?
– Sergio