Uncaught Typeerror: Cannot read Property 'value' of null // JS Error

Asked

Viewed 406 times

0

I’m making a website, and when I use Firebase it gives an error. I probably did something wrong with the Firebase script. This appears on the console:

Uncaught TypeError: Cannot read property 'value' of null
  at CadastrarDados (empreender:38)
  at HTMLButtonElement.onclick (empreender:131)

My code is this (I left without the firebase connection instructions to post here, but in the code this normal):

<!DOCTYPE html>
<html lang="pt_br">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Control Business</title>
        <link rel="stylesheet" href="/styles/main.css">
        <link rel="stylesheet" href="/styles/partials/page-give-classes.css">
        <link rel="stylesheet" href="/styles/partials/forms.css">
        <link rel="stylesheet" href="/styles/partials/header.css">
        <link href="https://fonts.googleapis.com/css2?family=Archivo:wght@400;700&amp;family=Poppins:wght@400;600&amp;display=swap" rel="stylesheet">
        <script src="https://www.gstatic.com/firebasejs/7.22.0/firebase-app.js"></script>
        <script src="https://www.gstatic.com/firebasejs/7.22.0/firebase-database.js"></script>
        <script>
            var firebaseConfig = {
    apiKey: "-",
    authDomain: "-",
    databaseURL: "-",
    projectId: "-",
    storageBucket: "-",
    messagingSenderId: "-",
    appId: "-"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);

var RefCads = firebase.database().ref("Cadastro");
 




function CadastrarDados() {
var nome = document.getElementById("txtNome").value;
var celular = document.getElementById("txtCelular").value;
var email = document.getElementById("txtEmai").value;
var razao = document.getElementById("txtRazao").value;
var cnpj = document.getElementById("txtCnpj").value;
var custo = document.getElementById("txtCusto").value;
var hist = document.getElementById("txtHist").value;

var resultado = RefCads.push ({
    nome : dNome,
    celular: dCelular,
    email: dEmail,
    razao: dRazao,
    cnpj: dCnpj,
    custo: dCusto,
    hist: dHist





});
alert("Cadastrado com sucesso, seu download começará automáticamente");

}



        </script>
    </head>

    <body id="page-give-classes">
        <div id="container">
            <header class="page-header">
                <div class="top-bar-container">
                    <a href="/">
                        <img src="/images/icons/back.svg" alt="Voltar">
                    </a>
            
                </div>
                <div class="header-content">
                    <strong>Empreenda conosco.</strong>
                    <p>Preencha seus dados nesse formulário e automáticamente você será redirecionado a página de download do app.</p>

                </div>
            </header>
            <main>
                    <fieldset>
                        <legend>Dados da sua Empresa ou Projeto</legend>
                    <div class="input-block">
                        <label for="nome">Seu nome completo</label>
                        <input name="nome" id="txtNome" >
                    </div>

                        <div class="input-block">
                            <label for="celular">Celular/Telefone para contato.
                            </label>
                            <input name="celular" id="txtCelular" type="number" >
                    </div>
                    <div class="input-block">
                        <label for="email">Email</label>
                        <small>(Preencha com um e-mail válido.)</small>
                        <input name="email" id="txtEmail" >
                    </div>
                    <div class="input-block">
                        <label for="razao">Razão Social</label>
                
                        <input name="razao" id="txtRazao" >
                    </div>
                <div class="input-block">
                    <label for="cnpj">CNPJ
                    </label>
                    <input name="cnpj" id="txtCnpj" type="number" >
                </div>
                    <div class="input-block">
                        <label for="custo">Custo operacional total de sua empresa.
                            <small>(R$)</small>
                        </label>
                        <input name="custo" type="number" id="txtCusto" >
                    </div>
                        <div class="textarea-block">
                            <label for="hist">Conte-nos um pouco sobre sua empresa ou seu projeto.</label>
                            <small>(Adoramos histórias!)</small>
                            <textarea name="hist" id="txtHist" ></textarea>
                        </div>
                    </fieldset>

                    
                        <footer>
                            <p>
                                <img src="/images/icons/warning.svg" alt="Aviso Importante">
                                Preencha todos os dados
                                <br>
                                Caso não possuir algum documento ou informação, preencha apenas seus dados pessoais.
                            </p>
                            <button onclick='CadastrarDados()'>Salvar Dados e Baixar o App</button>
                        </footer>
                    </main>
                </div>
  
            </body>
  
        </html>
  • The function getElementById is returning null rather than returning an element, because you are looking for the element txtEmai (lacked a l in the Email).

1 answer

0

You have to unblock the error. The exception is the type TypeError (MDN), than in Javascript. From the documentation:

Typeerror is activated when an operator or argument passed to a function is incompatible with the type expected by that operator or function.

So two examples of this error:

> "abc".funcaoQueNaoExiste()
Uncaught TypeError: "abc".funcaoQueNaoExiste is not a function

> const pessoa = {nome: "Vinicius", sobrenome: null}
undefined
> pessoa.nome.toUpperCase()
'VINICIUS'
> pessoa.sobrenome.toUpperCase()
Uncaught TypeError: Cannot read property 'toUpperCase' of null

Note that in the latter case, the value of pessoa.nome is null, that does not own a property called toUpperCase, that’s right null (MDN).

It’s exactly your case. You’re accessing .value of an object that is null, and that you probably didn’t expect me to be.

Looking further at the error it is possible to see the stacktrace (Sopt) error, which points us to function, file and line where the exception burst. It was in the var email = document.getElementById("txtEmai").value;. Maybe a typo (Wikipedia), because it should be "txtEmail".

Borrowing from the Greek: diagnōstikós. Ask the error, read it and most of the time it will point you the solution itself.

Browser other questions tagged

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