Error trying to access form fields

Asked

Viewed 31 times

0

I am studying Javascript and assembling this project according to what I am learning and searching, I am registering a movie name in a table through a form, when I fill this form returns the following error:

principal.js:42 Uncaught TypeError: Cannot read property 'value' of undefined
at HTMLButtonElement. (principal.js:42)
(anonymous) @ principal.js:42

Follow my HTML and Javascript:

//Retorna a lista de todos os elementos que combinam com o critério de busca.
var dvd = document.querySelectorAll(".info-dvd");



//algoritimo calcula quantas linhas existem na tabela
var quantidade = document.querySelectorAll(".filmes");
var total = document.querySelector(".info-total");
var valorTotal = quantidade.length;
total.textContent = valorTotal;



//Para cada elemento retornado executa uma ação dependendo do seu conteúdo.
dvd.forEach((e) => {
  var dvdInfo = e.textContent;
  switch (dvdInfo) {  //Troquei os if por um controle de fluxo switch por questão de legibilidade
    case "Sim": //fall through case para dvdInfo == "Sim" || dvdInfo == "Não".
    case "Não":
                 console.log("tudo funcionando");
                 break;
    case "":
                 e.textContent = "O Campo não pode estar vazio!"
                 console.log("campo está vazio");
                 e.style.color = "white";
                 e.classList.add("mensagemErro");

                 break;
    default:
                 e.textContent = "Preecha o campo com Sim ou Não";
                 console.log("campo invalido");
                 break;
  }
});

        //Impede que o botão recarregue a página e limpe o formulário!
        var botaoAdicionar = document.querySelector("#btn-enviar");
        botaoAdicionar.addEventListener("click", function(event){
        event.preventDefault();
        //criando novos linhas na tabela
        var form = document.querySelector("#form");
        var filme = form.filme.value;
        var genero = form.genero.value;
        var dvd = form.dvd.value;
        var dimas = form.dimas.value;
        var bruna = form.bruna.value;

        console.log(filme);
        console.log(genero);
        console.log(dvd);
        console.log(dimas);
        console.log(bruna);

    });
*{
    box-sizing: border-box;
 }

body, html{

    font-family: "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif;
    font-size: 14px;
}
.bgbody {
    background-image: url("../img/teste.jpg");
    background-position: top;;
    background-size: cover;
    background-repeat: no-repeat;
    display :block;
    width : 100%;
}


header{
    background-color: #333;
    height: 3em;
    color: #FFF;
    margin-bottom: 1em;
}

header h1{
    font-size: 2em;
    display:inline-block;
    vertical-align: middle;
}
header h2{
    font-size: 2em;
    display:inline-block;
    vertical-align: middle;
}

header .container:before{
    content: '';
    display:inline-block;
    height: 100%;
    vertical-align: middle;
}

.container{
    width: 60%;
    height: 100%;
    margin: 0 auto;
}

section{
    margin: 2em 0;
    overflow: hidden;
}

section h2{
    font-size: 3em;
    display: block;
    padding-bottom: .5em;
    border-bottom: 1px solid #ccc;
    margin-bottom: .5em;
}
.dimas{
    color: white;
    background:  #0e9af1;
}
.bruna{
    color: white;
    background: #00e673;
}
.info-total{
    color: white;
    font-weight: bold;
}
.total{
    color: white;
    font-weight: bold;
}
th{
    font-size: 20px;
}
td{
    text-align: center;
    font-size: 18px;
}
tr{
    text-align: center;
}
.custom{
    color: white;
    text-align: center;
}
.changeth{
    color: black;
}
table{
    background-color: white;
}
.mensagemErro{
    background: red;
    color: white;
}

label{
    font-size: 20px;
    font-weight: bold;
}

.btnEnviar{
    font-size: 20px;
    font-weight: bold;
}
.formTitle{
    font-size: 22px;
    color: green;
    font-weight: bold;

}
    <!DOCTYPE html>
    <html lang="pt-br">
        <head>
            <meta charset="UTF-8">
            <title>Brumas - Controle de Filmes & Séries</title>
            <link rel="icon" href="favicon.ico" type="image/x-icon">
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

            <link rel="stylesheet" type="text/css" href="css/index.css">

        </head>
        <body class="bgbody">
            <header>
                <div class="container">
                    <h1 class="a">Brumas - Controle de Filmes & Séries</h1>
                </div>
            </header>
            <main>
        <section class="container">
                            <h2>Controle</h2>
                    <table class="table table-bordered table-hover">
                        <thead class="thead-dark">
                            <tr>
                                <th class="changeth">Nome</th>
                                <th class="changeth">Gênero</th>
                                <th class="changeth">Possui DVD</th>
                                <th class="dimas">Dimas</th>
                                <th class="bruna">Bruna</th>
                            </tr>
                        </thead>
                        <tbody id="tabela-pacientes">
                            <tr class="filmes" >
                                <td class="info-nome">Invocação do Mal</td>
                                <td class="info-genero">Terror</td>
                                <td class="info-dvd">Sim</td>
                                <td class="info-dimas">Sim</td>
                                <td class="info-bruna">Sim</td>
                            </tr>

                            <tr class="filmes" >
                                <td class="info-nome">Invocação do Mal 2</td>
                                <td class="info-genero">Terror</td>
                                <td class="info-dvd">Sim</td>
                                <td class="info-dimas">Sim</td>
                                <td class="info-bruna">Sim</td>
                            </tr>

                            <tr class="filmes" >
                                <td class="info-nome">O Exorcista</td>
                                <td class="info-genero">Terror</td>
                                <td class="info-dvd">Sim</td>
                                <td class="info-dimas">Sim</td>
                                <td class="info-bruna">Sim</td>
                            </tr>

                            <tr class="filmes" >
                                <td class="info-nome">Jogos Vorazes</td>
                                <td class="info-genero">Ação/Ficção científica</td>
                                <td class="info-dvd">Sim</td>
                                <td class="info-dimas">Sim</td>
                                <td class="info-bruna">Sim</td>
                            </tr>
                            <tr class="filmes" >
                                <td class="info-nome">A Hora do Pesadelo</td>
                                <td class="info-genero">Terror</td>
                                <td class="info-dvd">Não</td>
                                <td class="info-dimas">Sim</td>
                                <td class="info-bruna">Sim</td>
                            </tr>
                            <tr class="filmes" >
                                <td class="info-nome"></td>
                                <td class="info-genero">Comédia</td>
                                <td class="info-dvd">Não</td>
                                <td class="info-dimas">Sim</td>
                                <td class="info-bruna">Sim</td>
                            </tr>
                            <tr class="filmes" >
                                <td class="info-nome">UM Príncepe em Nova York</td>
                                <td class="info-genero">Comédia</td>
                                <td class="info-dvd">Não</td>
                                <td class="info-dimas">Sim</td>
                                <td class="info-bruna">Sim</td>
                            </tr>
                            <tr class="total" >
                                <td></td>
                                <td></td>
                                <td></td>
                                <td class="bg-success total">Total:</td>

                                <td class="bg-dark info-total">0</td>
                            </tr>

                        </tbody>
                    </table>

            </section>
<hr>

<div class="container">
<h2 class="formTitle">Adicionar Filmes</h2>
<form  id="form">
  <div class="form-row">
    <div class="form-group col-md-6">
      <label id="filme">Nome do Filme</label>
      <input placeholder="Coloque o nome do Filme ou Franquia" type="text" class="form-control" id="inputEmail4" required>
    </div>

  </div>
  <div class="form-row">
        <div class="form-group col-md-2">
      <label name="genero">Gênero</label>
      <input placeholder="Coloque o Gênero do Filme. Ex: Terror" type="text" class="form-control" id="inputZip" required>
    </div>
        <div class="form-group col-md-2">
            <label name="dvd">Possui Dvd?</label>
            <input placeholder="Possui Media de DVD? Sim ou Não" type="text" class="form-control" id="inputZip" required>
        </div>
    <div class="form-group col-md-2">
      <label name="dimas">Dimas</label>
      <input type="text" class="form-control" id="inputZip" required>
    </div>
        <div class="form-group col-md-2">
      <label name="bruna">Bruna</label>
      <input type="text" class="form-control" id="inputZip" required>
    </div>
  </div>
  <div class="form-group">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" id="gridCheck" required>
      <label class="form-check-label" for="gridCheck">
        Confirmo envio do formulário
      </label>
    </div>
  </div>
  <button id="btn-enviar" type="submit" class="btn btn-primary btnEnviar">Enviar</button>
</form>
</div>
            </main>
            <!--<footer>
                <div class="jumbotron jumbotron-fluid bg-dark">
            <h3 class="custom">Copyright @ Brumas</h3>
            </div>
    </footer>-->

            <script src="js/principal.js">
</script>
            <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
            <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
            <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
        </body>
    </html>

2 answers

1

The problem lies in this part of the code:

var form = document.querySelector("#form");
var filme = form.filme.value;
var genero = form.genero.value;
var dvd = form.dvd.value;
var dimas = form.dimas.value;
var bruna = form.bruna.value;

Note that you are trying to get the elements referring to the fields by the form itself. And this is possible according to the documentation:

You can also get the form’s element by using its name attribute as a key of the form. [...]

In free translation:

You can also get form elements using the attribute name as a key to form.

This means that as long as the fields in your form have an attribute name, you can access them from the form element.

The problem is that none of your fields have the attribute name. Take, for example, the first of them:

<div class="form-group col-md-6">
  <label id="filme">Nome do Filme</label>
  <input placeholder="..." type="text" class="form-control" id="inputEmail4" required>
</div>

Note that although you have a id, does not have an attribute name. To correct, simply put the attribute name as, in this case, filme. Thus:

<div class="form-group col-md-6">
  <label id="filme">Nome do Filme</label>
  <input name="filme" placeholder="..." type="text" class="form-control" id="filme" required>
</div>

In addition, the id as filme also (to refer to the attribute for of <label>).

Just do it for each of the fields.


But it is worth noting that the documentation itself (which I mentioned earlier) recommends the use of the property elements to access the fields from which to get them directly through the form instance, since this last approach can make room for name conflicts.

So instead of using, for example:

form.filme.value;

Utilize:

form.elements.filme.value;

So that filme is the name country. :)

To learn more about the element <form>, see the documentation. There is a lot of important information on this page.

  • Face excellent answer! But I discovered my mistake I was pasting name on label instead of input, lack of attention my! One question if I don’t put the Elements can give conflict is this?

  • 1

    Yes, the form contains several other properties besides the fields, which can generate conflicts. When using elements, which is a property that contains exclusively the fields, you eliminate the possibility of conflicts. : ) @dimascamillo

-1

Another simpler approach would be to get the elements straight by the field ids you want Ex.

var email = Document.getElementByid('inputEmail4'). value

Browser other questions tagged

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