HTML5 validation when the input type is not “submit”

后端 未结 9 1312
醉酒成梦
醉酒成梦 2020-11-29 01:42

I\'m using HTML5 for validating fields. I\'m submitting the form using JavaScript on a button click. But the HTML5 validation doesn\'t work. It works only when then input ty

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 01:55

    I wanted to add a new way of doing this that I just recently ran into. Even though form validation doesn't run when you submit the form using the submit() method, there's nothing stopping you from clicking a submit button programmatically. Even if it's hidden.

    Having a form:

    This will trigger form validation:

    function doFancyStuff() {
        $("#submit-button").click();
    }
    

    Or without jQuery

    function doFancyStuff() {
        document.getElementById("submit-button").click();
    }
    

    In my case, I do a bunch of validation and calculations when the fake submit button is pressed, if my manual validation fails, then I know I can programmatically click the hidden submit button and display form validation.

    Here's a VERY simple jsfiddle showing the concept:

    https://jsfiddle.net/45vxjz87/1/

提交回复
热议问题