preventDefault - 不按我的预期工作

时间:2011-04-10 15:57:27

标签: javascript jquery

我有这个代码,我的想法是将数据发送到validation.php,但不提交表单。点击下面的代码简单无效。我的问题是,我不能允许提交默认操作,因为当按下按钮时,无论验证在PHP中是否有效,它都会重新加载到初始页面。如果我将.click更改为.submit,则会重新加载页面。

 <script type="text/javascript" language="javascript">

   $(document).ready(function() {

      $("#customForm").click(function(event){
         event.preventDefault();
         $.post("validation.php", {
             nameRegist: $('#nameRegist').val(),
             emailRegist: $('#emailRegist').val(),
             myPasswordRegist: $('#myPasswordRegist').val(),
             pass2Regist: $('#pass2Regist').val()
         });
      });

   });
   </script>


<form method="post" id="customForm" action="">
            <div>
                <label for="name">Name</label> 
                <input id="nameRegist" name="nameRegist" type="text" /> 
                <span id="nameInfo">Insira o seu nome</span>
            </div>
            <div>
                <label for="email">E-mail</label> 
                <input id="emailRegist" name="emailRegist" type="text" /> 
                <span id="emailInfo">Insira um email válido por favor!</span>
            </div>
            <div>
                <label for="myPassword">Password</label> 
                <input id="myPasswordRegist" name="myPasswordRegist" type="password" /> 
                <span id="myPasswordInfo">Insira pelo menos 4 letras e sem espaços</span>
                <div id="bar" style="width: 234px; height: 20px;"></div>
            </div>
            <div>
                <label for="pass2">Confirm Password</label> 
                <input id="pass2Regist" name="pass2Regist" type="password" /> 
                <span id="pass2Info">Confirme a password</span>
            </div>
            <div></div>
            <div>
                <input id="send" name="send" type="submit" value="Send" />
            </div>
        </form>

http://emprego.xtreemhost.com/login/emprego.php - 请点击绿色按钮(注册表),然后提交(对不起服务器抱歉)

1 个答案:

答案 0 :(得分:2)

$(document).ready(function() {

      $("#customForm").submit(function(event){
         $.post("validation.php", {
             nameRegist: $('#nameRegist').val(),
             emailRegist: $('#emailRegist').val(),
             myPasswordRegist: $('#myPasswordRegist').val(),
             pass2Regist: $('#pass2Regist').val()
         });
         event.preventDefault();
         return false;
      });
   });