html5 required and jQuery submit()

后端 未结 9 594
我在风中等你
我在风中等你 2020-12-09 07:56

I\'m trying to implement html5 into a form, but I came with a problem when I submit the form through jquery and try to use the html5 \"required\" attribute.

Here is

相关标签:
9条回答
  • 2020-12-09 08:35

    You are right. HTML5 validation works only when submit is triggered by user. this is how it is. :(

    you need write a your own custom method on submit. OR there is a good plugin you can use which validates fields according html5 attributes.

    here is the plugin link

    0 讨论(0)
  • 2020-12-09 08:37

    Answer from https://stackoverflow.com/a/30124479/7915308

    <!DOCTYPE html>
    <html>
    <body>
    
    <form name="testform" action="action_page.php">
    E-mail: <input type="email" name="email" required><br/>
    <a href="#" onclick="javascript:console.log(document.testform.reportValidity());return false;">Report validity</a><br/>
    <a href="#" onclick="javascript:console.log(document.testform.checkValidity());return false;">Check validity</a><br/>
    <a href="#" onclick="javascript:if(document.testform.reportValidity()){document.testform.submit();}return false;">Submit</a>
    </form>
    
    </body>
    </html>

    0 讨论(0)
  • 2020-12-09 08:37

    You could call a function instead and use that function to check if all the nodes with the required attribute have a value.

    There are some plugins available to do this: http://thechangelog.com/post/1536000767/h5validate-html5-form-validation-for-jquery

    0 讨论(0)
  • 2020-12-09 08:43

    Here an exemple of my personnal solution:

    var form = $('#loginform');
    
    // Trigger HTML5 validity.
    var reportValidity = form[0].reportValidity();
    
    // Then submit if form is OK.
    if(reportValidity){
        form.submit();
    }
    
    0 讨论(0)
  • 2020-12-09 08:51

    I did the following

    <form>
        ...
        <button type="submit" class="hide"></button>
    </form>
    
    <script>
        ...
        $(...).find('[type="submit"]').trigger('click');
        ...
    </script>
    

    ¡it works!

    0 讨论(0)
  • 2020-12-09 08:52

    I had exactly the same problem. I had a single button that I had deliberately set NOT to be a submit because it was on first click revealing a form. On a second click of the same button $('form[name=xxx]').submit(); was firing and I found as well that the HTML5 validation doesn't work.

    My trick was to add a line of code so that after my first click of this button occurs I change its type to submit dynamically.

    $("#btn").attr("type","submit");
    

    Which worked like a charm!

    0 讨论(0)
提交回复
热议问题