Javascript - 如果未满足最小和最大条件,则阻止表单提交

时间:2016-05-26 19:30:44

标签: javascript jquery html

如果输入的数字不在最小值和最大值之间,我使用javascript在用户点击表单提交按钮时显示错误。问题是,当您单击提交按钮时,表单将提交,无论如何。你能看一下下面的代码并告诉我需要添加的内容。如果不满足最小和最大条件,我需要阻止表单提交。

HTML

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
        <script src="validation.js"></script></head>
<body>


<form name="form1" >
          <label>Enter Amount</label>
          <input id="amount" type="number"  value="0" min="5" max="10" step="1"/>
          <p id="error"></p>
          <br/>
          <label>Charity you wish to donate to</label>
          <input type="text" name="charity"></input>
          <br/>
          <button id="save_choice"  onclick="amountFunction()">Save Choice</button>
          <button><a href="#" target="_blank">Save Choice</a></button> 
            </form>

<p id="error"></p>

</body>
</html>

的javascript

     var inpObj = document.getElementById("amount");
if (inpObj.checkValidity() == false) {
    document.getElementById("error").innerHTML = inpObj.validationMessage;
    return false
} else {
    document.getElementById("error").innerHTML = "Input OK";
    return true
} 

}

1 个答案:

答案 0 :(得分:-1)

利用页面中已有jQuery的事实,您可以使用事件侦听器。

$("form[name=form1]").on("submit", amountFunction);

function amountFunction(ev){
     var inpObj = document.getElementById("amount");
     if (inpObj.checkValidity() == false) {
         ev.preventDefault();
         $("#error").text("Value should be between " + $(inpObj).attr("min") + " and " + $(inpObj).attr("max"));
         return false;
     } else {
         document.getElementById("error").innerHTML = "Input OK";
         return true;
     } 
}

注意:事件监听器声明应该在页面加载完毕后运行。

相关问题