简体   繁体   中英

Submit form with JS do not perform basic validation

Why when I am using javascript the basic HTML inputs validation not performed?
Say the min max attributes.

Here the HTML:

<form action="#" method="get">Quantity (between 1 and 5):
    <input type="number" name="quantity" min="1" max="5">
    <br />
    <input type="submit" value="with HTML">
</form>
<button id="sender">with JS</button>

JS:

$("#sender").click(function (event) {
    $("form").submit();
});

And live example: http://jsfiddle.net/txP4R/2/

You have to trigger the normal submit button:

$("#sender").click(function (event) {
    $('input[type="submit"]').trigger('click');
    event.preventDefault();
});

See this fiddle: http://jsfiddle.net/gopeter/txP4R/3/

You need to associate the button with the form and check if the form is valid. See this jfiddle:

http://jsfiddle.net/txP4R/5/

The HTML:

<form action="#" method="get" id="form">Quantity (between 1 and 5):
    <input type="number" name="quantity" min="1" max="5">
    <br />
    <input type="submit" value="with HTML">
</form>
<button id="sender" form="form">with JS</button>

And the jQuery:

$("#sender").click(function (event) {
    if (("#form")[0].checkValidity()) {
        $("#form").submit();
    }
});

Edit: Good catch A. Wolff

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