简体   繁体   English

进行html验证,而无需在提交表单时调用javascript函数。

[英]Do html validation without calling javascript function on submission of form.

I have a form which has a textarea: 我有一个带有文本区域的表格:

<form id="hello">
  <textarea id="Testarea" required></textarea>
</form>
<button id="myButton" type="submit" value="Submit">Click me!
</button>

When the user submits the form, I listen to it via a jquery handler: 当用户提交表单时,我通过一个jQuery处理程序来监听它:

$("#myButton").click(function () {
    alert("blah");
});

However if the textarea is empty, I want an error to be thrown without calling my function. 但是,如果textarea为空,我希望在不调用函数的情况下引发错误。 Right now, my function is called even if the textarea is empty. 现在,即使textarea为空,我的函数也会被调用。 https://jsfiddle.net/8dtsfqp0/ https://jsfiddle.net/8dtsfqp0/

Use a submit handler on the form, not a click handler on the button. 在表单上使用submit处理程序,而不在按钮上使用click处理程序。

Here is the order of execution when you click on a submit button: 单击提交按钮时,执行顺序如下:

  • Button's click handler is called. Button的单击处理程序将被调用。 If it calls event.preventDefault() , the process stops. 如果调用event.preventDefault() ,则过程停止。
  • The form is submitted, which performs the following steps: 提交表单,该表单执行以下步骤:
    • Validate input fields. 验证输入字段。 If any validation fails, the process stops. 如果任何验证失败,则过程停止。
    • Call the form's submit handler. 调用表单的提交处理程序。 If it calls event.preventDefault() , the process stops. 如果调用event.preventDefault() ,则过程停止。
    • The form data is sent to the server. 表单数据被发送到服务器。

So if you want to prevent your function from being called, it has to be after the "Validate input fields" step. 因此,如果要防止调用函数,则必须在“验证输入字段”步骤之后。 So change your code to: 因此,将您的代码更改为:

$("#hello").submit(function () {
    //Throw error if textarea is empty
  alert("Her");
});

Fiddle 小提琴

you can try this: 您可以尝试以下方法:

$("#myButton").click(function () {
if($('#Testarea').val().trim().length > 0)
{
return true;
}
else
{
alert("empty text box");
return false;
}

});
<script type="text/javascript">
document.getElementById("myButton").addEventListener("click", myFunction);
var problem_desc = document.getElementById("Testarea");
function myFunction() {
    if (problem_desc.value == '') {
        alert("blank");
        return false;
    }
    else{
    alert("working");
    }
}
</script>

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

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