Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
preventDefault(); block the submit action of my form in vanila Javascript

I am trying to validate my form keeping the styles that I make for it, thus avoiding the default behavior of the form. But it turns out that when I hit the submit button my form is not sent.

Removing the preventDefault(); to the form, the function that I performed to check it is not executed.

const $form = document.querySelector('.contact-form'),
  $user = document.querySelector('#name')
let counter = 0;

$form.addEventListener('submit', e => {
  e.preventDefault();
  checkInputs();
})

$user.addEventListener('click', (e) => {
  const groupControl = $user.parentElement,
    p = groupControl.querySelector('p');
  p.classList.remove('show-error-message');
})
const showErrorFor = (input, error) => {
  const groupControl = input.parentElement,
    p = groupControl.querySelector('p');
  p.innerText = error;
  p.classList.add('show-error-message');
}

const validFields = (input) => {
  const groupControl = input.parentElement,
    p = groupControl.querySelector('p');
  p.classList.remove('show-error-message');
  counter++;
}
const checkInputs = () => {
  const userValue = $user.value.trim();

  userValue === "" ? showErrorFor($user, "Porfavor ingrese su nombre!") : validFields($user);
}
const isValidNumberPhone = (phone) => {
  return /^[0-9]*(\.?)[0-9]+$/.test(phone);
}
<pre><code>
    <form action="./mail/send.php" method="POST" class="contact-form" autocomplete="off" novalidate="novalidate">  <!-- #simple_form -->
        <div class="info-user">
            <div class="control">
                <input type="text" autocomplete="off" class="input-control" id = "name" placeholder="Ingrese su nombre *" required>
                <p class="error"></p>
            </div>
            <div id="success"></div>
            <button type="submit" class="botones btn-primary" id="send_button">Enviar</button>
        </div>
    </form>

    
    </code></pre>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use event.preventDefault() and then grab the form element and submit with document.getElementById("myForm").submit();, assuming you give the form tag an id of myForm

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!