0
我正在使用JavaScript進行表單驗證。 提交時,那些無效的輸入字段的背景顏色會更改爲紅色。填寫此字段並在另一個輸入字段中鍵入時,前一個字段的紅色背景色應消失。目前情況並非如此。它只會在再次提交時消失。如何讓這可能使bg顏色在另一個字段中輸入時變回正常狀態?如何禁用背景色輸入字段
// Return true if the input value is not empty
function isNotEmpty(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.length !== 0); // boolean
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
/* If "isValid" is false, print the errorMsg; else, reset to normal display.
* The errorMsg shall be displayed on errorElement if it exists;
* otherwise via an alert().
*/
function showMessage(isValid, inputElement, errorMsg, errorElement) {
if (!isValid) {
// Put up error message on errorElement or via alert()
if (errorElement !== null) {
errorElement.innerHTML = errorMsg;
} else {
alert(errorMsg);
}
// Change "class" of inputElement, so that CSS displays differently
if (inputElement !== null) {
inputElement.className = "error";
inputElement.focus();
}
} else {
// Reset to normal display
if (errorElement !== null) {
errorElement.innerHTML = "";
}
if (inputElement !== null) {
inputElement.className = "";
}
}
}
形式:
<td>Name<span class="red">*</span></td>
<td><input type="text" id="name" name="firstname"/></td>
<p id="nameError" class="red"> </p>
的提交:
<input type="submit" value="SEND" id="submit"/>
的CSS:
input.error { /* for the error input text fields */
background-color: #fbc0c0;
}
更新: 我想這家B UT似乎不工作:
function checkFilled() {
var inputVal = document.querySelectorAll("#offerteFirstname, #offerteLastname, #offertePhone, #offertePoster, #offerteStreet").value;
if (inputVal == "") {
document.querySelectorAll("#offerteFirstname, #offerteLastname, #offertePhone, #offertePoster, #offerteStreet").style.backgroundColor = "red";
}
else{
document.querySelectorAll("#offerteFirstname, #offerteLastname, #offertePhone, #offertePoster, #offerteStreet").style.backgroundColor = "white";
}
}
checkFilled();
這對一個單一的輸入ID很好用;但我有幾個輸入字段與不同的ID。我怎樣才能使它適用於所有這些領域? – nuet 2014-11-24 11:54:23
上面的問題已更新 – nuet 2014-11-24 12:01:33