生活随笔
收集整理的這篇文章主要介紹了
js表单验证,给出友好的提示
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
js驗證表單
注意:
只做非空驗證, 只是個小demo學習思想,onblur onfocus onsubmit的使用,給出友好提示網上有很多有良好,強大的控件,用于用戶輸入
代碼實現
<script
>function check_form(form
) {var els
= form
.getElementsByTagName("input");for(var i
= 0; i
< els
.length
; i
++) {if (typeof(els
[i
].getAttribute("onblur")) == "function" || typeof(els
[i
].getAttribute("onblur")) == "string") {if (!check_item(els
[i
])) {return false;}}}return true;}function check_item(obj
) {var value
= obj
.value
.trim();var msgBox
= obj
.parentNode
.getElementsByTagName("label")[0];switch (obj
.name
){ case "name": if (value
== "") {msgBox
.className
= "change_color";msgBox
.innerText
= "填寫姓名";return false;}case "age":if (value
== "") {msgBox
.className
= "change_color";msgBox
.innerText
= "填寫年齡"; return false;}case "birthday":if (value
== "") {msgBox
.className
= "change_color";msgBox
.innerText
= "填寫生日"; return false; }}return true;}function check_focus(obj
) {var msgBox
= obj
.parentNode
.getElementsByTagName("label")[0];msgBox
.className
= "change_color";msgBox
.innerText
= "";}</script
>
<!DOCTYPE html
>
<html><head><meta charset
="utf-8" /><title></title
><style>table
{width
: 500px
;text
-align
: center
;}td
{border
-style
: none
;}.change_color
{color
: red
;}</style
><!-- 類選擇器
, 不符合條件
, 改變label的顏色
--> <script></script
></head
><body><form action
="post" onsubmit
="return check_form(this)"><table align
="center" border
="1px" cellpadding
="0" cellspacing
="0"><tr><td>姓名
</td
><td><input type
="text" name
="name" onblur
="check_item(this)" onfocus
="check_focus(this)" /><label
class="change_color"></label
></td
></tr
><tr><td>年齡
</td
><td><input type
="text" name
="age" onblur
="check_item(this)" onfocus
="check_focus(this)" /><label
class="change_color"></label
></td
></tr
><tr><td>性別
</td
><td><input type
="radio" name
="gender" value
="男" checked
="checked"/>男
<input type
="radio" name
="gender" value
="女"/>女
</td
></tr
><tr><td>生日
</td
><td><input type
="text" name
="birthday" onblur
="check_item(this)" onfocus
="check_focus(this)"/><label
class="change_color"></label
> </td
></tr
> <tr><td colspan
="2"><input type
="submit" value
="提交"/><input type
="reset" value
="重置" /></td
></tr
> </table
></form
></body
>
</html
>
-
填年齡時,onfocus 清除后面的提示
-
填寫完整
-
提交check_form判斷,地址欄顯示提交數據
總結
以上是生活随笔為你收集整理的js表单验证,给出友好的提示的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。