简体   繁体   中英

Disable submit button on click after form validation

I have a form, which has a jquery form validation.. what i need is the submit button should get disabled when i submit the form once the validation is done..

<form action="#" method="post" id="myform" name="myform">
    Location: <input name="location" type="text" />
    Site: <input name="site" type="text" />
    Age: <input name="age" type="text" />
    Gender <input name="gender" type="text" />
    <input name="button" type="submit" class="myButton" id="button" value="Submit" />
</form>

here is my form JsFiddle

Not sure why you want to disable the submit button but using jQuery you could do

$('input[type="submit"]').prop('disabled',true);

Typically you either wouldnt have a submit button, or else submit the form and the page will reload!

UPDATE

To stop people from reposting the values by refreshing the page as you wrote in comments, redirect the user to the page without the values posted!

 header('/same_page.php');

you want to do the action on form.submit. Not sure if you need to add form.valid() there as a check, but I always do it like that. Afterwards you can return true or false.

  • True: The browser proceeds with the link and action specified in the form
  • False: The browser stops (when you have validation errors)

Here the code:

$('#myform').submit(function() {
    if (!$('#myform').valid()) return false;

    $('#myform input[type=submit]').attr("disabled", "disabled");
    return true;
});

I've also updated your fiddle with that code, so you can try it out

after you validate the form, use:

$( "#button" ).click(function(event) {
        if($('#myform').valid()) {
            $(event.target).attr("disabled", "disabled");
        }
    });

If you want to disable once the form which you want to validate is valid, then you can disable the submit button like this

$("#myForm").validate({
  submitHandler: function(form) {
    // do other stuff for a valid form
    $('#myform input[type=submit]').attr("disabled", "disabled");
    form.submit();
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM