Input required attribute does not work after using jquery

Asked

Viewed 934 times

1

Hello,

When using jquery to disable the Submit button after being sent once the required attribute in input no longer works.

HTML

<form id="ajax" action="#teste" method="POST">
        <p class="remodal-text">Nome</p>
        <input type="text" name="nome" required>
         <p class="remodal-text">E-mail</p>
        <input type="email" name="email" required>
         <p class="remodal-text">Assunto</p>
        <input type="text" name="assunto" required>
         <p class="remodal-text" required>Mensagem</p>
        <textarea name="mensagem" name="mensagem"></textarea>
        <input type="submit" value="Enviar" class="btn-submit" >
      <div id="enviado" style="width: 100%; height: 60px;"></div>

        </form>

JS

 $(function(){
     $(".btn-submit").click(function () {
       $(".btn-submit").attr("disabled", true);
       $('#ajax').submit();
     });
   });

Example in Codepen: http://codepen.io/flashpremium/pen/gpZZRv

1 answer

3


You can use the event submit in place of click to send the form, example:

$(function(){
    $("#ajax").on('submit', function() {
        $(".btn-submit").attr("disabled", true);
    });
});

When adding a Listener in the event of submit from your form, you ensure that the validations within it are all fired, after all, they run before this event. Now when you use click on the form button, it would be as if you were talking: "Hey, just listen when this button is clicked, no matter if the form was sent or not". Therefore, the event fires only with the button, before any event of the form itself, what hinders the validation of the same.

Including, using the submit to fire your form AJAX allows you to use the standard functionality of the browsers to send a form by pressing the key Enter.

Note: I removed the line $("#ajax").submit() since we are now treating the very event of Submit, it will already be sent anyway.

  • That solves the problem, thank you Kazzkiq!

Browser other questions tagged

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