I have about 120 inputs

<input type="text" />

I'm going to fill some of them with some text, while the others will be empty. Is there any way to use a submit button that will make all empty inputs change in background color?. Any help will be appreciated.

有帮助吗?

解决方案

It can easily be done using jQuery if you prefer. Here's the solutions using both javaScript and 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

其他提示

This should work:

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top