使用jquery进行表单验证最简洁的方法记录

[ 2013-08-30 16:41:12 | 作者: admin ]
字号: | |

<html>
  <head>
    <title>Validate empty fields</title>
    <style type="text/css">
      body{font-family:"Trebuchet MS",verdana;width:450px;}
      .error{ color:red; }
      #info{color:#008000;font-weight:bold; }
    </style>
  </head>
  <body>
    <form>
      <fieldset>
        <legend><strong>Personal</strong></legend>
        <table>
          <tbody>
            <tr>
              <td>Name:* </td>
              <td><input type="text" class="required" /></td>
            </tr>
            <tr>
              <td>Address:* </td>
              <td><input type="text" class="required"/></td>
            </tr>
            <tr>
              <td>City: </td>
              <td><input type="text"/></td>
            </tr>
            <tr>
              <td>Country:* </td>
              <td><input type="text" class="required"/></td>
            </tr>
          </tbody>
        </table>
      </fieldset>
      <br/>
      <span id="info"></span>
      <br/>
      <input type="button" value="Check" id="check" />
    </form>
    <script type="text/javascript" src="../jquery.js"></script>
    <script type="text/javascript">

      $(document).ready(function(){
      var dataValid=false;
      $('#info').html('');//然后将结果提示也设置为空;
      $('.required').blur(function(){//对于required类的元素,如果失去焦点了,则....
      var cur=$(this);//获取当前元素
      cur.next('span').remove();//然后将错题提示的<span>给移走,不管他之前是什么;
      if($.trim(cur.val())=='')
        {//判断如果输入为空;
          cur.after('<span class="error">Mandatory field!</span>');//则在输入框后添加错题提示信息;
          dataValid=false;
        }else{dataValid=true;}
    });
    $('#check').click(function(){//点击了Check按钮之后,执行....
    if(dataValid)
          {
            $('#info').html('Validation OK');//提示通过验证
          }});
  });
    </script>
  </body>
</html>
评论Feed 评论Feed: http://blog.xg98.com/feed.asp?q=comment&id=2116

这篇日志没有评论。

此日志不可发表评论。