Error onclick Javascript

Asked

Viewed 583 times

1

When trying to perform the click event, returns the following message in the console:

Uncaught Typeerror: Cannot read Property 'value' of null at calculatorWidth (square.js:3) at Htmlinputelement.onclick (index.html:10)

<html>
        <head>
        <meta charset="utf-8">
        <title>Exercicios</title>
        <script type="text/javascript" src="quadrado.js"></script>
    </head>
    <body>  
        Números <input type="text" name="txtNumeros">
        <input type="button" value="Calcular quadrado!" onclick="calcularQuadrado()">
    </body>
    </html>

Filing cabinet js square.

    function calcularQuadrado() {
    var numeros = document.getElementById("txtNumeros").value;
    numeros = numeros.split("-");
    for (i=0; i=numeros.length; i++){
        quadrado = parseInt(numeros[i])*parseInt(numeros[i]);
        document.write("O quadrado de "+numeros[i]+ " é "+quadrado+"<br>");
    }
}

2 answers

3


HTML error

It is a syntactic error, because the attribute onclick is not valid for the tag input.

More about tag properties input here:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input

The correct is to use the onclick as property of a tag <button>, your problem will be solved this way.

Information about onclick in the button (in English):

https://www.w3schools.com/jsref/event_onclick.asp

Error in Javascript

There is an error in your Javascript, as quoted by Bruno Romualdo. You are using the property name in his input, and making the reference getElementByID in your Javascript. As the name says, this call makes the relation by ID, not by name. To resolve, you need to add the property ID to his input.

More about the getElementByID

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

  • Precise, fast and functional! Thank you truly!

2

You are using:

document.getElementById("txtNumeros").value; // pegar o elemento por id

to get the value of the input, but its input is not with the id txtNumeros and yes with the attribute name:

<input type="text" name="txtNumeros">

change it to

<input type="text" name="txtNumeros" id="txtNumeros"> // adicionando o atributo id no final

that will already work.

Browser other questions tagged

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