文章摘要
这篇文章介绍了如何使用JavaScript来验证用户提交的用户名和密码是否为空,并通过form表单提交验证结果。文章分为两种方法: 1. 方法一通过`checkUser()`函数检查`username`和`password`字段是否为空。如果输入为空,函数提示用户并返回`false`;否则返回`true`。form表单设置为`method='post'`,并通过`onclick`属性调用`checkUser()`函数。 2. 方法二同样使用`checkUser()`函数,但逻辑稍有不同。如果`username`或`password`为空,函数提示用户并返回`false`;否则提交form。需要注意的是,当form提交失败时,函数不会返回`false`,导致用户无法收到提交失败的提示。 文章的重点在于如何通过JavaScript实现form验证,并提供了两种不同的实现方法供参考。
方法一:JS判断提交
js函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function checkUser(){ var result = document.getElementById( "userid" ).value; var password = document.getElementById( "userpassid" ).value; if (result == "" ){ return false ; } if (password == "" ){ alert( "密码不能为空" ); return false ; } else { return true ; } } |
form表单
1 2 3 4 5 | < form id = "formid" name = "myform" method = 'post' onsubmit = "return checkUser();" > < input type = "text" value = "" class = "text2" name = "username" id = "userid" /></ td > < input type = "password" value = "" class = "text2" name = "userpass" id = "userpassid" /></ td > < input type = "submit" value = "" class = "btn2" /> </ form > |
方法二:
1 2 3 4 5 6 7 8 9 10 11 12 13 | function checkUser(){ var result = document.getElementById( "userid" ).value; var password = document.getElementById( "passid" ).value; if (!result){ alert( "用户名不能为空" ); return false ; } if (!password){ alert( "密码不能为空" ); return false ; } document.getElementById( "formid" ).submit(); } |
form表格的写法,需要写id
1 | < form id = "formid" method = 'post' > |
button按钮的写法如下:
1 | < input type = "button" value = "" class = "btn2" onclick = "checkUser();" /> |
© 版权声明
文章版权归作者所有,未经允许请勿转载。