简体   繁体   English

使用JS提交表单不执行基本验证

[英]Submit form with JS do not perform basic validation

Why when I am using javascript the basic HTML inputs validation not performed? 为什么当我使用javascript时,基本的HTML输入验证没有执行?
Say the min max attributes. 说最小最大属性。

Here the HTML: 在这里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: JS:

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

And live example: http://jsfiddle.net/txP4R/2/ 现场例子: 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/ 看到这个小提琴: 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: 看到这个jfiddle:

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

The HTML: 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: 和jQuery:

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

Edit: Good catch A. Wolff 编辑:好抓A.沃尔夫

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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