简体   繁体   English

JS setCustomValidity第一次不起作用

[英]JS setCustomValidity not work at first time

I want to make a custom validity message to my form, and there are some problem. 我想在表单中添加自定义有效性消息,但存在一些问题。

The validity message will show after click two times. 单击两次后,将显示有效性消息。 and if I don't input correct word "text" first time, then it will not submit anymore. 如果我第一次没有输入正确的单词“文本”,那么它将不再提交。 what's the problem in my code. 我的代码有什么问题。

JS: JS:

 function a(){ jQuery("#text")[0].setCustomValidity(""); if (jQuery("#text").val() == "text"){ return confirm('sure?'); } jQuery("#text")[0].setCustomValidity("Incorrect"); return false; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action="/" method="post" onsubmit="return a();"> <input type='text' id="text"/> <input type="submit" value="submit"/> </form> 

Please try to check below solution: 请尝试检查以下解决方案:

 $(document).on('click',"#submit_btn", function() { if($("#text").val() === "text") return confirm('sure?'); else $("#text")[0].setCustomValidity("Incorrect"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action="/" method="post"> <input type='text' id="text"/> <input type="submit" value="submit" id="submit_btn"/> </form> 

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

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