Required input attribute does not work after using jquery

1

Hello,

When using jquery to disable the submit button after being sent once the required input in the input does not work anymore.

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: link

    
asked by anonymous 03.08.2015 / 19:16

1 answer

3

You can use the submit event instead of click to submit the form, eg:

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

By adding a listener to the submit tails event of your form, you ensure that the validations within it are all triggered, after all, they run before this event. Now when you use click in the form button, it would be as if you were talking: "Hey, listen only when this button is clicked, no matter if the form was sent or not." . So, the event only triggers with the button, before any event of the form itself, which hinders the validation of it.

Even using submit to trigger your AJAX form lets you use the default functionality of browsers to submit a form by pressing Enter .

Note: Note that I removed the line $("#ajax").submit() since since we are now dealing with the submit event itself, it will already be sent anyway.     

03.08.2015 / 20:48