简体   繁体   中英

ajax, jquery javascript html form validation wont work with an onclick

At a very high level here is what happens

This code works just fine ...

<div id='showme'></div>

<div id='theform'>
   <form ...>
   <input required ...
   <input required ...
   <input id='thebutton' type='submit' ....
   </form>
</div>

The above code works fine. If I click submit and form field is empty I get the standard notification.

Throw this in and it partially works ...

$(document).ready(function(){

   $('#thebutton').click(function() {
      $('#theform').hide();
      $('#showme').html('<img src="loading2.gif">');
   });
.
.
.

And the image show just like I want it to. However, I lose all the checks against the required fields.

Can someone please assist with this? AlL I want to do is show a loading animated gif when the user click the submit button.

Thanks

JT

Thats because you're hiding the form no matter what onclick and then putting the loader gif. you would do better to bind to the form's submit event, check validation with javascript to see if the form is valid and only then proceed to show the loading state. Using native HTML5 js validation you can ask an input element if it's valid with the checkValidity() method like this.

    if(requiredField.checkValidity() === false) //required field was not valid so you can't show loading gif yet

I think this does it. Could one of you gurus confirm?

   $('#thebutton').click(function(e) {
      var isvalidate = $('#contentform')[0].checkValidity();
      if (isvalidate) {
         event.preventDefault();
         $('#theform').hide();
         $('#showme').html('<img src="loading2.gif" alt="Loading" style="width:300px;">');
         $('#contentform').submit();
      }
   });

Or am I doing something wrong ?

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