需求:必填输入框校验。文本框失去焦点时,如果内容为空,边框标红提示;有内容则边框恢复黑色。 用到事件:focus获得焦点,blur失去焦点。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm29.aspx.cs" Inherits="WebApplication1.WebForm29" %>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
<script>
$(function () {
$("input:text").blur(function () {
if ($(this).val() == "") {
$(this).attr("style","border-color:red");
}
else {
$(this).attr("style", "border-color:black");
}
});
$("input:text").focus(function () {
if ($(this).val() != "") {
$(this).attr("style", "border-color:black");
}
});
});
</script>
</head>
<body>
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
</body>
</html>
Code language: HTML, XML (xml)
说明:
$("input:text"):表单选择器,选中所有单行文本框blur:光标离开输入框,判断value是否为空,设置边框颜色focus:光标进入输入框,有内容就恢复黑色边框
Previous: 实现搜索框字体提示功能
Next: RadioButton操作