1

I have a form which is accepting 2 fields and filling each field is compulsory. I have used the required attribute to achive this .

Enter A:<input type="text" name="a" required><br>

Enter B:<input type="text" name="b" required><br>

<button type="submit" class="sub" value="submit">

The parameter required save the line of codes to check the blank values and when without filling the value anyone clicks on the submit button it shows please fill out this field.

but I want to disable the submit button as soon as the form gets submitted.

I am using jquery for that

$('.sub').click(function(){

       $('.sub').prop('disabled', true);
       $('#dvLoading').show();

});

but the problem is even when the fields are not filled and on click of the submit button the button gets disables.

What can be done in that case so that the button only gets disabled when each fields are filled and form is getting submitted.

Navankur Chauhan
  • 407
  • 6
  • 22

1 Answers1

1

You have two choices, the first one is to subscribe to submit event and your handler won't be triggered until the form is invalid:

$(function () {
 $('#myform').submit(function () {
  $('.submit').prop('disabled', true);
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
    <input type="text" required>
    <input type="text" required>
    <input type="submit" value="submit" class="submit">
</form>

The second option is to use checkValidity() to ensure the form is valid before disabling:

$(function () {
        $('.submit').click(function () {
            var form = document.getElementById("myform");
            if (form.checkValidity() !== false) {
                $('.submit').prop('disabled', true);
            }
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
    <input type="text" required>
    <input type="text" required>
    <input type="submit" value="submit" class="submit">
</form>
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • Awesome :),It worked for me ,Thanks , I tried using the class to get to the form but failed , seems like it can be done only by the ID. I tried $('#form')[0].checkValidity() !== false) instead of getElementById() and appending [0] worked for me as seems like it returns some array in that case. – Navankur Chauhan Jan 07 '17 at 14:50
  • 1
    @NavankurChauhan, you should be able to select the form by classname, try again :). Also, consider using the `submit` event, instead of `click`, you might not need to make checks in this case. – Max Koretskyi Jan 07 '17 at 15:01