JavaScript Function Can not read property 'value' of null

2

I created a function in javascript, and it works when the field txtDiaVencimento is filled, however not always this field will be filled, when it is not filled it returns me the following error:

  

Can not read property 'value' of null

Here's a piece of code:

if (document.getElementById("<%= txtDiaVencimento.ClientID %>").value != null) {
    var data = document.getElementById("<%= txtDataInicio.ClientID %>").value;
    var data_inicio = data.substring(0, data.indexOf("/"));
    var dia_vencimento = document.getElementById("<%= txtDiaVencimento.ClientID %>").value;
}

I try to check if it is null, so that it does not enter the function, but it still returns the error. And he does not continue the rest of the function. The error is always in document.getElementById("<%= txtDiaVencimento.ClientID %>").value when it is empty, because either the txtDiaVencimento or txtDiaFim is filled.

    
asked by anonymous 26.10.2017 / 13:40

1 answer

8

The right thing is to check that the getElementById return is null and not the value of it.

if (document.getElementById("<%= txtDiaVencimento.ClientID %>") != null) {
    var data = document.getElementById("<%= txtDataInicio.ClientID %>").value;
    var data_inicio = data.substring(0, data.indexOf("/"));
    var dia_vencimento = document.getElementById("<%= txtDiaVencimento.ClientID %>").value;
}
    
26.10.2017 / 13:55