输入框为空红色提示功能

需求:必填输入框校验。文本框失去焦点时,如果内容为空,边框标红提示;有内容则边框恢复黑色。 用到事件: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:光标进入输入框,有内容就恢复黑色边框

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注