如何禁用背景色输入字段

问题描述:

我正在使用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">&nbsp;</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(); 

这里例如它

<input type="text" id="subEmail" onchange="checkFilled();"/> 

,现在你也可以javascript输入

function checkFilled() { 
var inputVal = document.getElementById("subEmail").value; 
if (inputVal == "") { 
    document.getElementById("subEmail").style.backgroundColor = "white"; 
} 
else{ 
    document.getElementById("subEmail").style.backgroundColor = "red"; 
} 
} 

checkFilled(); 

在这里工作demo

+0

这对一个单一的输入ID很好用;但我有几个输入字段与不同的ID。我怎样才能使它适用于所有这些领域? – nuet 2014-11-24 11:54:23

+0

上面的问题已更新 – nuet 2014-11-24 12:01:33

尝试

$(formElement).on('keyup','input.error', function(){ 
    if(<values changed>){ 
     $(this).removeClass('error'); 
    } 
});