1

Can anyone please help me resolve this conflict with my javascript validation?

The form does not submit. But if I remove onsubmit="return btnSubmitPD_OnClick() it redirect the form correctly. But of course I need that function.

Here's my code:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){ 
$('#Submit').click(function() {
    var emailVal = $('#email').val();
    $.post('checkemail.php', {'email' : emailVal}, function(data) {
        if(data=='exist') {
            alert('in'); return false;
        }else{
            $('#form1').submit();
        }

    });
});});
</script>
<script type="text/javascript"> 
function appIsEmail(str){
    var at="@";
    var dot=".";
    var lat=str.indexOf(at);
    var lstr=str.length;
    var ldot=str.indexOf(dot);
    if (str.indexOf(at)==-1) return false; 

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
    if (str.indexOf(at,(lat+1))!=-1) return false;
    if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
    if (str.indexOf(dot,(lat+2))==-1) return false;
    if (str.indexOf(" ")!=-1) return false;

     return true;
}

function btnSubmitPD_OnClick(){
    frmReg = document.getElementById("form1");

    if (!appIsEmail(frmReg.email.value)){
        alert("Please enter a valid email address!");
        frmReg.email.focus();
        return false;        
    }

    return true;
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="view.php" onsubmit="return btnSubmitPD_OnClick()">
  <p>
    <input type="text" name="email" id="email" />
  </p>
  <p>
    <input type="button" name="Submit" id="Submit" value="Submit" />
  </p>
</form>
</body>
</html>
4

1 回答 1

0

几件事:

最好将提交事件绑定到您的表单,而不是提交按钮上的单击事件,这是为了满足用户在电子邮件文本字段上按 Enter 的情况:

$('#form1').submit(function() { // change from $('#Submit').click

然后在新的submit处理程序中,调用电子邮件验证方法:

var emailVal = $('#email').val();
if(btnSubmitPD_OnClick() === false) return false;

然后,为避免无限submit循环,您需要更改:

else{
            $('#form1').submit();
        }

else{
            $('#form1')[0].submit(); // native submit on form element
        }

或者正如 mplungjan 在他的评论中指出的那样,只需更改您的

<input type="button" name="Submit" id="Submit" value="Submit" />

使用type="submit"

<input type="submit" name="Submit" id="Submit" value="Submit" />

并添加

if(btnSubmitPD_OnClick() === false) return false;

在您致电之前$.post

于 2012-07-26T09:46:18.923 回答