Error of Javascript Code

Asked

Viewed 53 times

1

Well, I have the following javascript code:

< script type = "text/javascript" >
  function teste() {
    var date1 = document.getElementById("data");
    var date2 = document.getElementById("data2");
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
    alert(diffDays);
  } < /script>

In html I have the following code:

Reserve of: <input type="date" name="data" id="data" />

Up until: <input type="date" name="data2" id="data" onblur="teste()" />

I would like to know why I next put the date in the inputs does not appear a alert saying the number of days.

2 answers

2

@Gonçalo, according to what he had talked to you in the other Post, you will have to do so, after the focus of the dataFinal field is removed you take the event from blur and calculate.

function calculaDiferenca(dataInicial, dataFinal) {
    var date1 = new Date(dataInicial);
    var date2 = new Date(dataFinal);
    var timeDiff = Math.abs(date2.getTime() - date1.getTime());
    var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
    alert(diffDays + ' dias');
}

(function() {

    var dataFinal = document.getElementById('dataFinal');

    dataFinal.addEventListener('blur', function() {
        var dataInicial = document.getElementById('dataInicial').value;

        if(!dataInicial) {
            alert('informe a data inicial e depois a final!');
            return;
        }

        var dataFinal = document.getElementById('dataFinal').value;

        if(!dataFinal) {
            alert('informe a data final!');
            return;
        }

        calculaDiferenca(dataInicial, dataFinal);
    });

})();

Follows the jsfiddle.

  • 1

    Solved, thank you very much!

0

Notice when you use document.getElementById("data") That in itself doesn’t give you the value of input. You have to get the property .value to know the value.

Then, since you want to use the getTime() you have to convert that string document.getElementById("data").value gives you a date again. In this case you should use

var date2 = new Date(document.getElementById("data2").value);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.