我無法確保我的表單完全填寫完畢。使用多種版本的JavaScript驗證表單
下面是HTML:
<div id="username_input">
<span>User name:</span> <input id="username" onclick="changeBackground('#ffffff', this.id)" type="text" name="firstname" />
<small id="username_error_message">please input username</small>
</div><!-- End of div id username_input -->
<div id="email_input">
<span>Email:</span> <input id="email" onclick="changeBackground('#ffffff', this.id)" type="text" name="email" />
<small id="email_error_message">please input email</small>
</div><!-- End of div id email_input -->
<div id="textarea">
<textarea id="textarea_body" onclick="clearTextarea()" rows="5" cols="120"></textarea>
</div><!-- End of div id textarea -->
<div id="submit_button">
<input id="button" type="submit" name="Submit" value="Post Comment" />
</div><!-- End of div id button -->
所有我想要做的就是確保用戶沒有留下一個空的輸入。
這裏是我遇到了一個問題之前,迄今:
function inputCheck() {
/* This is to check if the values, username - email
and text area body, in the input form are filled in */
if($('username').value.length == 0 || $('email').value.length == 0 || $('textarea_body').value.length == 0) {
if($('username').value.length == 0) {
alert("Invalid username");
return false;
} else if ($('email').value.length == 0) {
alert("Invalid email");
return false;
} else {
alert("Invalid post");
return false;
}
} else {
return true;
}
我想這三種警報框一次露面。我遇到的問題是,它會查看第一個if語句,然後跳出JavaScript代碼。
我稍後會告訴他們「請輸入電子郵件」或「請輸入用戶名」,但因爲我不能再多一個,如果我不知道這是怎麼回事。
我不想使用js庫。
考慮避免onclick屬性並使用JavaScript設置處理程序。 – 2010-11-07 00:31:10
P元素(段落)比DIV更適合你的情況 – 2010-11-07 00:35:43
爲什麼我應該避免點擊?什麼是更好的替代品? – Philip 2010-11-07 01:49:34