簡體   English   中英

javascript更改多個輸入背景色

[英]javascript change multiple input background color

我大約有120個輸入

<input type="text" />

我將用文本填充其中一些,而其他文本將為空。 有什么方法可以使用提交按鈕來使所有空輸入的背景顏色發生變化? 任何幫助將不勝感激。

如果願意,可以使用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演示

jQuery演示

這應該工作:

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();

單擊此處獲取JSFIDLE演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM