0

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>
  • You need to fetch your /mail/send.php through ajax if you want to use e.preventDefault() and prevent page refresh. – Cesare Polonara Apr 08 '22 at 17:07
  • 2
    That's 100% not correct – DCR Apr 08 '22 at 17:10
  • you need to have your validation function return a value depending on whether validation passed or not, and only call `preventDefault` if validation failed – Robin Zigmond Apr 08 '22 at 17:14
  • Or call `preventDefault()` like you're doing, and then have your validation function trigger `submit()` directly on the form node if the validation passes. – Daniel Beck Apr 08 '22 at 17:16

1 Answers1

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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
DCR
  • 14,737
  • 12
  • 52
  • 115
  • this won't work in itself, because the submit handler will still be called and the default prevented – Robin Zigmond Apr 08 '22 at 17:13
  • I do this all the time, it works fine – DCR Apr 08 '22 at 17:14
  • *shrug*, if you say so - maybe I'll have a go in CodePen or something to see if it works. But if it does I'm a bit baffled as to how. – Robin Zigmond Apr 08 '22 at 17:15
  • why? the default behavior is stopped once, that let's you do things to your vars and then you submit the form – DCR Apr 08 '22 at 17:17
  • This does work, but it's confusingly worded; I think people aren't understanding that you mean calling `submit()` after passing validation. – Daniel Beck Apr 08 '22 at 17:18
  • yes, but when "you submit the form", it should call all submit handlers, so the default gets prevented again because that's what's in the handler. Thinking about it again, this is basically going to cause an infinite loop. – Robin Zigmond Apr 08 '22 at 17:18
  • Nope. If you call submit() directly it will not call the event handler. If you fire a click event on the click button, _that_ would trigger the event handler, but just calling submit() directly does not. – Daniel Beck Apr 08 '22 at 17:19
  • OK, that's weird, so event handlers only get called if the event is triggered "manually", not if the event is triggered programatically? If so that strikes me as really weird, but I guess you guys must be right. Every day is a school day, as they say! – Robin Zigmond Apr 08 '22 at 17:20
  • Note I'm referring to the fact that in the OP, the event handler is for the submit event on the form. If it was for the click on the submit button, what you're saying makes perfect sense, and that could be a good way to handle this situation - but then I wouldn't have questioned it! – Robin Zigmond Apr 08 '22 at 17:21
  • 1
    @RobinZigmond It is not correct to deal with form submission in the `click` handler of the submit button because a form can be submitted in other ways besides clicking a button - - in the right configuration, you can submit a form by pressing ENTER. That would of course not trigger any `click` event. The proper way to handle a `submit` event is with a `submit` event handler. See the linked answer. – Scott Marcus Apr 08 '22 at 17:24
  • The problem is that preventDefault prevents me from submitting my form when selecting the submit button, but if I remove the preventDefault from the form, the validation function I made, with its respective styles, does not execute. I'm very confused. – Bryan Ortiz Apr 08 '22 at 17:24
  • @BryanOrtiz **See the linked answer.** You need to only prevent the form submission during validation when you have failed that validation. You are preventing the form submission immediately and then only running validation code (which doesn't cause submission). You have no code anywhere to cause the submission if you pass validation. – Scott Marcus Apr 08 '22 at 17:26
  • 1
    @RobinZigmond see here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event "The event is not sent to the form when calling the form.submit() method directly". This is the common behavior for script-initiated events as opposed to user-initiated ones – Daniel Beck Apr 08 '22 at 17:29
  • @DanielBeck thank you, that is what I was looking for. Weird, but at least it seems it's a special case for me submit event, not something that applies to all events. – Robin Zigmond Apr 08 '22 at 17:50
  • @ScottMarcus I agree regarding click vs submit - I only thought of this because it would make sense in terms of what I was being told (before I was shown the docs explaining there's a special case here for the submit event). – Robin Zigmond Apr 08 '22 at 17:51
  • 1
    @RobinZigmond nope, the same thing applies to most interactions, not just form submits -- user-initiated events tend to be treated very differently than script-initiated ones. – Daniel Beck Apr 08 '22 at 18:23