我有一個登錄表單,但我想檢查,如果字段爲空,那麼不要提交。我在提交時沒有返回false,但瀏覽器仍然加載一個新頁面。我怎麼能阻止呢?如何防止提交,如果輸入爲空與javascript
JS:
var username = document.getElementById('usernameField');
var password = document.getElementById('passwordField');
var loginBtn = document.getElementById('loginBtn');
var infoBox = document.getElementById('formInfo');
var isEmpty = /^\s*$/;
var addEventTo = function(id, type, fn, capture) {
if (document.addEventListener) {
id.addEventListener(type, fn, capture);
} else {
id.attachEvent('on'+type, fn);
}
};
function checkIfAllEmpty() {
var loginForm = document.getElementById('loginform'),
allInputs = loginForm.getElementsByTagName('input'),
max = allInputs.length,
i;
for (i = 0; i < max; i++) {
if (allInputs[i].type !== 'submit') {
if (allInputs[i].match(isEmpty)) {
infoBox.innerHTML = 'All your fields are empty';
return false;
}
}
}
}
//addEventTo(loginBtn, 'click', checkIfAllEmpty, false);
if (document.addEventListener) {
loginBtn.addEventListener('submit', checkIfAllEmpty, false);
} else {
loginBtn.attachEvent('onsubmit', checkIfAllEmpty);
}
HTML:
<p id="formInfo"></p>
<form id="loginForm" method="post" action="#">
<fieldset id="loginFieldset">
<legend>Sign in</legend>
<ol>
<li>
<label for="usernameField">Username</label><input type="text" placeholder="Enter username" id="usernameField" />
<span>Please type in your username</span>
</li>
<li>
<label for="passwordField">Password</label><input type="password" placeholder="Enter password" id="passwordField" />
<span>Please type your password</span>
</li>
<li>
<input type="submit" value="Sign in" id="loginBtn" />
</li>
</ol>
</fieldset>
</form>
非常感謝
你能提供你的HTML代碼的形式嗎?或者你動態地創建表單? –
Hi @Naama Katiee:我已經添加了HTML ... – Shaoz