Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

307
Visualizações
How to validate HTML elements when submitting through JQuery?

I have an HTML form as shown below with some form fields and a submit and a delete button:

enter image description here

There is also a floating component which appears whenever there are changes in the form as shown in the same diagram with text: You have unsaved changes. This is a common component which appears for all the forms in my website.

When I submit the form using the form's Submit button, it validates all the fields as per the validations.

(for example: <input type="number" min="0"> will check that the number should be positive)

But if I submit the form from the Save button on the floating element, it does not checks for any validation, and just posts the request.

I tried using the following code, but the reportValidity() function doesn't do anything.

if (!form.checkValidity()) {
    form.reportValidity();
}

form.checkValidity() and form.reportValidity() both are returning false when I do a console.log.

What am I missing here, and how can I fix this?

P.S. I tried this on chrome v98.

Edit: Adding HTML code:

<form method="post" action="/products/manage/{{.Product.ID}}/submit/">
    <div class="form-group col-md-5">
        <label>Product Quantity</label>
        <input type="number" min="0" name="ProductQuantity" value="{{if .Product}}{{.Product.Qunatity}}{{else}}10{{end}}">
    </div>
    <button type="submit" class="btn btn-success" value="Submit">Submit</button>
    <button type="submit" class="btn btn-danger" value="Delete" formaction="/products/manage/{{.Product.ID}}/delete/">Delete</button>
</form>

Save button calls this function:

function submitForm(form, url) {
    const form = $(form)[0]
    if (!form.checkValidity()) {       //<- Added the code here
        form.reportValidity();
    }
    var serialized = serializeForm(form);
    // Do some more things then use HTTP to request the API
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can easily use the jQuery event handlers do the work for you. A simplified example below:

  1. Give your form some identifier (example: id="form1")

  2. Catch the click event on button click

  3. Trigger the submit event to submit that form

    $('.unsavedChangesBtn').on('click',function(){
       $('#form1').submit();
    });
    

In below example you can submit the form either by clicking the submit button or the save button.

$('document').ready(function(){

  $('#form1').on('submit',function(){
    alert("SUBMITTED");
  });

  $('.unsavedChangesBtn').on('click',function(){
     $('#form1').submit();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="form1" action="javascript:void(0);">
    <div class="form-group col-md-5">
        <label>Product Quantity</label>
        <input type="number" min="0" name="ProductQuantity" value="{{if .Product}}{{.Product.Qunatity}}{{else}}10{{end}}">
    </div>
    <button type="submit" class="btn btn-success" value="Submit">Submit</button>
    <button type="submit" class="btn btn-danger" value="Delete" formaction="/products/manage/{{.Product.ID}}/delete/">Delete</button>
</form>

<button class="unsavedChangesBtn"> SAVE </button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda