2014-05-17 97 views
0

所以表單驗證工作正常,但我無法將其發送到PHP文件。我假設它與返回錯誤/真實和結束有關。表單不會返回true,也不會發送到PHP

function validateForm(contact) { 
    var name = document.getElementById('name').value 
    var email = document.getElementById('email').value 
    var msg = document.getElementById('message').value 

    if (name == '') 
     { 
     $('.nameerror').html('Please provide your name').fadeIn(1000);  

     }else if 
     (!validateName(name)) { 
      $('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000); 
     } 


    if (email == '') 
     { 
     $('.emailerror').html('Please provide your email').fadeIn(1000);  
     }else if 
     (!validateEmail(email)) { 
      $('.emailerror').html('Invalid email format').fadeIn(1000);  
     } 



    if (msg == '') 
     { 
     $('.msgerror').html('What can we help you with?').fadeIn(1000); 
     } 


return false; 

if($.trim($('.nameerror').text()) == ''){ 
    return true;  
} 

}; 
+0

會不會JS降你的函數,只要你返回的第一個值 - 因此從來沒有真正讓你最後'if'聲明? – Fluffeh

+0

在這個地方放置'return false;'的原因是什麼?我認爲這是問題 – shatheesh

+0

避免同時使用'Javascript'和'jQuery'。選擇他們中的任何一個。 – Ranjith

回答

2

我想代碼的最後一節應該這樣寫:

if($.trim($('.nameerror').text()) == '') 
{ 
    // You can do stuff here first if everything is good. 
    return true;  
} 
else 
{ 
    // Or you can do stuff here for a failed submission. 
    return false; 
} 

你之前的最後一個退出函數if語句進行檢查。

0

您必須使用此代碼:

function validateForm(contact) { 
    var name = document.getElementById('name').value 
    var email = document.getElementById('email').value 
    var msg = document.getElementById('message').value 

    if (name == '') { 
     { 
     $('.nameerror').html('Please provide your name').fadeIn(1000);  

     }else if 
     (!validateName(name)) { 
      $('.nameerror').html('Only letters and spaces are allowed').fadeIn(1000); 
     } 
     return false; 
} 


    if (email == '') { 
     { 
     $('.emailerror').html('Please provide your email').fadeIn(1000);  
     }else if 
     (!validateEmail(email)) { 
      $('.emailerror').html('Invalid email format').fadeIn(1000);  
     } 
    return false; 
} 

    if (msg == '') { 
     $('.msgerror').html('What can we help you with?').fadeIn(1000); 
     return false; 
} 

if($.trim($('.nameerror').text()) == ''){ 
    return true;  
} 

};

0

而不是檢查以查看某個特定元素是否包含html ...爲什麼不設置標誌?這使得一切都變得更簡單。


function validateForm(contact) { 
    var name = document.getElementById('name').value 
    var email = document.getElementById('email').value 
    var msg = document.getElementById('message').value 
    var flag = true; 

    //do this for each of your if statements 
    if(there is an error case) { 
     //do whatever you want to the DOM 
     flag = false; 
    } 
return flag; 

} 
相關問題