[英]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: 单击提交按钮时,执行顺序如下:
event.preventDefault()
, the process stops. event.preventDefault()
,则过程停止。 event.preventDefault()
, the process stops. event.preventDefault()
,则过程停止。 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");
});
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.