2014-02-15 32 views
0

我有大約120輸入的JavaScript更改多個輸入背景顏色

<input type="text" /> 

我要填補其中的一些使用一些文本,而其他人將是空的。 有什麼辦法可以使用提交按鈕,使所有空輸入改變背景顏色? 任何幫助將不勝感激。

+1

是的,這是可能的。你有什麼嘗試? – Teemu

+0

我仍然卡住,因爲我真的是新的JavaScript:( – user2044626

回答

1

它可以很容易地使用jQuery,如果你喜歡做。這裏是使用javaScript和jQuery的解決方案。

HTML:

<input type="text" /> 
<input type="text" /> 
<input type="text" /> 
<input type="text" /> 
<input type="text" /> 

<input type="button" id="submitButton" value="Submit" /> 
//for javaScript 
<!-- <input type="button" id="submitButton" value="Submit" onclick="validateField();" /> --> 

JavaScript的:

function validateField(){ 
    var textFields = document.getElementsByTagName("input"); 
     for(var i=0; i < textFields.length; i++){ 
     if(textFields[i].type == "text" && textFields[i].value == "") 
     { 
      textFields[i].style.backgroundColor = "red"; 
     } 
     else { 
      textFields[i].style.backgroundColor = "white"; 
     } 
    } 
} 

的jQuery:

$("#submitButton").click(function(){ 
    $("input").each(function(){ 
     if($(this).attr("type") == "text" && $(this).val() == "") 
     { 
      $(this).css("background-color", "red"); 
     } 

     else { 
      $(this).css("background-color", "white"); 
     } 
    }); 
}); 

javaScript Demo

jQuery Demo

+0

謝謝,最佳答案+1 – user2044626

+0

還包括使用javaScript的解決方案。您可以檢查! –

0

這應該工作:

function verifyInputs() { 
    var inputs = document.querySelectorAll('input'); 
    for (var i=0; i<inputs.length; i++) { 
     if (inputs[i].type == 'text' && inputs[i].value == "") { 
      inputs[i].style.backgroundColor = 'red' 
     } 
    } 
} 
// This should be triggered on dom load/window load or in case when you want to check and mark the inputs with color 
verifyInputs(); 

Click here for JSFIDLE demo

+0

感謝您的及時響應,但我仍然無法使用提交按鈕驗證這些值 – user2044626

+0

您是否已將此函數綁定到'submit button'的' click' event? – alix