Javascript function Cannot read Property 'value' of null

Asked

Viewed 12,449 times

3

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

Cannot read Property 'value' of null

Follow 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 even so it returns the error. And it does not continue the rest of the function. The mistake is always in the document.getElementById("<%= txtDiaVencimento.ClientID %>").valuewhen it is empty, because either txtDiaVencing or txtDiaFim is filled.

  • 3

    You should check if the getElementById is null, not its value. That is, remove the .value who is in the condition of if.

  • Mariana, can you ask me a question? In the post you say: "it works when the txtDiaVencing field is filled", That means the field has some value or that he was created visually?

  • I can take yes, it is because it has a condition, or it is filled or the field txtDataFim, but this way that you helped me, it enters the if correctly, and does not give the problem, and is working the way it should. I don’t know if I was clear.

  • @marianac_costa, when you don’t fill txtDiaVencimento, he enters if? if yes, this is a problem? if possible edit your question with the html in question. (can by a console.log('entrou'); , inside the if to check).

  • If I do not fill it does not enter, it was already solved, the answer helped me.

1 answer

9


The right is to check if the return getElementById is null and not its value.

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;
}
  • It worked right in my function, I’m still picking up enough javascript, rs. Thanks.

Browser other questions tagged

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