javascript error Cannot read Property 'value' of null

Asked

Viewed 1,094 times

0

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

Cannot read Property 'value' of null

Follow 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 still it returns the error. in the part var distribuir = document.getElementById("txtDistribuir").value is always coming Undefined, I can’t get the value that is in this textbox.

  • You can post the HTML portion of the page?

  • are various inputs, know how to take the value of several and add them?

  • If you catch "Cannot read Property 'value' of null" on that line it is because the id there is no. If the html is generated by JSP which is what it looks like by the syntax, I advise you to view the generated source code on the page, as it may be different from what you imagine.

1 answer

1


You need to continue using Clientid within If. There’s a difference between

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

The first searches exactly for the string "txtDistribuir" on the page, while the second searches for a string dynamically generated by 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);
        }
    }

Browser other questions tagged

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