简体   繁体   中英

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:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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