2012-12-20 32 views
-1
報表

我現在的語句:多重如果形式

if (recaptcha == '' || name == '' || email == '' || emailCheck || emailVerify || priority == 'pap' || topic == 'pat' || message == 'message') { 
    $('#incorrmsg').html("Please fill in the fields").slideDown("slow"); 
} else { 
    //else statemnt goes here 
}​ 

這裏的問題是,它只能與一個ID做到這一點。

我想將它更改爲這樣一句話:

if (name == '') { 
    $('#incorrname').html("Please fill in your name").slideDown("slow"); 
} 

if (email == '' || emailCheck || emailVerify) { 
    $('#incorremail').html("Please fill in and verify your email").slideDown("slow"); 
} 

if (priority == 'pap') { 
    $('#incorrpri').html("Please pick a priority").slideDown("slow"); 
} 

if (topic == 'pat') { 
    $('#incorrtop').html("Please pick a topic").slideDown("slow"); 
} 

if (message == 'message') { 
    $('#incorrmess').html("Please type in your message").slideDown("slow"); 
} else { 
    //else statemnt goes here 
}​ 

我想顯示在同一時間的所有消息如果在該領域的錯誤。
這意味着我不想使用else if語句。

那麼我該怎麼做?

+1

問題是什麼? – undefined

+0

你所擁有的代碼看起來像是在做你正在做的事情。你試過了嗎? – Guffa

+1

正如'古法'所說,所顯示的代碼似乎是這樣做的。如果它不能在http://jsfiddle.net上展示這個問題,就可以把小提琴放在一起。 – Nope

回答

0

你給自己更多的麻煩比你需要的特異性。使用數組,在驗證過程中將所有錯誤推送到它上面,然後在輸出過程中顯示錯誤。

var err = new Array(); 
if(email == '' || emailCheck) { 
    err[] = 'Yo, your email is messed up.'; 
} 

if(err.length > 0) { 
    for (var i=0;i<err.length;i++) 
    { 
     $('#errors').append('<li>' + err[i] + '</li>'); 
    } 
} 

此外,你可以看看jQuery Validation plugin。當我開始學習時,它非常有幫助,既便於實現,又瞭解如何最佳構建JavaScript函數。

+0

雅,我是小白。我不想用驗證插件,因爲它已經爲你做了這些東西。我想學習:D和謝謝。 – Yoosuf

+0

學習很好。你可以學習的最重要的事情之一就是不要嘗試重新發明輪子,並且藉此機會使用並閱讀其他人提供的工具作爲學習機會。 – dyelawn