문제

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