Frage

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.

War es hilfreich?

Lösung

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

Andere Tipps

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top