Validate form attributes and submit data with Jquery

Asked

Viewed 86 times

1

Hello, everyone! I’m making a Javascript and Jquery API application, using localstorage to store the data. I inserted some validation attributes in the inputs (required and Pattern) and inserted the onclick event in the tag button to submit the data in the table.

I found that the validation attributes are not activated because the onclick event is activated first. So I researched and followed some guidelines to put the onsubmit event on the tag form, to be validated first and then the data to be submitted and played on the table and localstorage.

The problem is that the data are validated, submitted, stored in localstorage, but do not populate the table.

I already tried to change the tag button to input and insert the type "Submit", insert the onsubmit into the form with the onclick on the button/input, and nothing.

Then I went to Jquery and tried to do a separate function calling the sign-up function, through event, if, and nothing works. The most that happens is the case above (respect the validations and store the content in localstorage, but do not populate the table), and I need the table to contain the data, too.

If anyone can help me, I’d appreciate it!

Follow the code below:

HTML

<section id="form">"
        <form id="form-aluno" onsubmit="cadastrar()">
<!--        <form id="form-aluno">-->
          <h2>Dados do aluno</h2>
          <p>Página destinada ao cadastro, edição, remoção e exibição dos alunos matriculados no Colégio Fiorentin. </p>

          <label for="aluno">Nome:</label>
          <input type="text" id="aluno" name="nome" class="valida-form" required="required" />

          <label for="idade">Idade:</label>
          <input type="text" required="required" id="idade" class="valida-form" name="numbers" pattern="[0-9]+$" />

          <label for="serie">Série:</label>
          <select id="serie" name="serie" class="valida-form" required="required">
            <option value="" data-default disabled selected>Selecione</option>
            <option value="1º ano - ensino médio">1º ano - ensino médio</option>
            <option value="2º ano - ensino médio">2º ano - ensino médio</option>
            <option value="3º ano - ensino médio">3º ano - ensino médio</option>
          </select>

          <label for="faltas">Faltas:</label>
          <input type="number" id="faltas" class="valida-form" name="faltas" required="required" />

          <input type="hidden" id="txtId" class="valida-form" name="id" required="required">

<!--          <button type="submit" id="cadastro" onclick="cadastrar()">Cadastrar</button>-->
<!--          <button type="button" id="cadastro">Cadastrar</button>-->

          <input type="submit" id="cadastro" value="Cadastrar" />
          <button  style="display:none" type="button" id="alterar" onclick="modificar()">Modificar</button>
        </form>
      </section>

      <div>
        <table id="tabela">
          <thead>
            <tr>
              <th>Aluno</th>
              <th>Idade</th>
              <th>Série</th>
              <th>Faltas</th>
              <th>Situação</th>
            </tr>
          </thead>
          <tbody id="tbody-alunos">

          </tbody>
        </table>
  </div>

JS

let botaoAdiciona = $("#cadastro");
let formAluno = $("#form-aluno");

function cadastrar() {

  let alunos = localStorage.alunos == null ? [] : JSON.parse(localStorage.alunos);

    let nome = $("#aluno").val();
    let idade = $("#idade").val();
    let serie = $("#serie").val();
    let faltas = $("#faltas").val();

      alunos.push({
        aluno: nome,
        idade: idade,
        serie: serie,
        faltas: faltas,
        situacao: faltas > 50 ? "Reprovado por faltas" : "Aprovado"
      });

      localStorage.alunos = JSON.stringify(alunos);

  listar();

  alert(`Dados do(a) aluno(a) ${nome} adicionados!`);


  formAluno[0].reset();
}


function listar() {

  // document.addEventListener("click", function (e) {

    // e.preventDefault();

    let alunos = localStorage.alunos == null ? [] : JSON.parse(localStorage.alunos);

  let tabela = $("#tbody-alunos");
  tabela.html("");
  alunos.forEach(dados => {
    tabela.append(`
            <tr>
                <td>${dados.aluno}</td>
                <td>${dados.idade}</td>
                <td>${dados.serie}</td>
                <td>${dados.faltas}</td>
                <td>${dados.situacao}</td>
                <td>
                    <button id="botao-editar" onclick="editar(${dados.nome})">Editar</button>
                    <button id="botao-apagar" onclick="excluir(${dados.nome})">Excluir</button>
                </td>  
            </tr>
        `);
  });
  // });
}

1 answer

1


How you can cancel the Submit action from the com form event.preventDefault() within the attribute onsubmit:

onsubmit="cadastrar(); event.preventDefault()"

What is happening is that the form is being submitted and the page reloaded, and with that the student list is empty because there is no action to list what the localStorage has when the page is loaded.

  • Placing Event.preventDefault() inside onsubmit stores the data in the localstorage, but I have to click again on the sign-up button to appear in the table. After that, no command works anymore.. :/

  • I don’t understand. When you click on "register" the table is updated.

  • Then, there is an event within the list() function with the same command (preventDefault()). Hence, I believe that when I inserted preventDefault() in onsubmit, this command was repeated twice (once in HTML and once through the list() function). I took the event from the list() function and it’s working right!!!

  • Thank you! (I accidentally hit enter) I broke my head about 4h yesterday and this whole morning, but it was hahaha Just answering your last question, @sam, I wanted, when clicking register, to have the validation of HTML attributes first and, if everything was right, the form data were submitted to the table and stored in the localstorage. I was only getting validation and storage. So I decided to take this event from the list function and went :D

  • Dial, @Sam! Thank you!!

Browser other questions tagged

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