javascript error Can not read property 'value' of null

0

I created a function in javascript, but it returns the following error:

  

Can not read property 'value' of null

Here's a piece of code:

function Distribuir(control) {
            var tr = $(control).parents('tr');

            var quantidade = $(tr).find("input[id*='txtQuantidade']").val();
            var distribuir = document.getElementById("txtDistribuir").value;
            if (document.getElementById("<%= txtDistribuir.ClientID %>") != null) {
                var distribuir = document.getElementById("txtDistribuir").value;
                resultado = distribuir - quantidade;
                $(tr).find("input[id*='txtDisponivel']").text(resultado);
            }
        }

I am already doing the treatment to see if it is null, but it still returns the error. in the var distribuir = document.getElementById("txtDistribuir").value part is always coming undefined, I can not get the value that is in that textbox.

    
asked by anonymous 26.03.2018 / 20:32

1 answer

1

You must continue to use the ClientID within 'If'. There is a difference between

document.getElementById("txtDistribuir")
document.getElementById("<%= txtDistribuir.ClientID %>"

The first one looks exactly at the "txtDistribute" string on the page, while the second looks for a dynamically generated string through Web Forms.

Try the following:

   function Distribuir(control) {
        var tr = $(control).parents('tr');

        var quantidade = $(tr).find("input[id*='txtQuantidade']").val();
        var distribuir = document.getElementById("txtDistribuir").value;
        if (document.getElementById("<%= txtDistribuir.ClientID %>") != null) {
            var distribuir = document.getElementById("<%= txtDistribuir.ClientID %>").value;
            resultado = distribuir - quantidade;
            $(tr).find("input[id*='txtDisponivel']").text(resultado);
        }
    }
    
27.03.2018 / 03:00