使用Javascript中的函数在NULL时更改文本框的颜色

时间:2014-06-25 10:04:08

标签: javascript html colors textbox

我有一个小问题要问。如果在点击“验证”按钮后它们保持为NULL,我想将几​​个文本框的背景颜色从WHITE更改为RED。禁止在输入中添加任何类或ID。我被提示使用“document.querySelectorAll”

以下是我的HTML代码:

<div id="formtovalidate">
    <div><input type="text" value="Billy Bob" /> Name</div>
    <div><input type="text" value="" /> Email Address</div>
    <div><input type="text" value="98195" /> ZIP Code</div>
    <div><input type="text" value="" /> Mailing Address</div>
    <div><input type="text" value="" /> Telephone Number</div>
    <div><input type="password" value="abc123" /> Password</div>
</div>

<div><button id="validate">validate</button></div>

这是我试过的代码:

window.onload = function() {
    document.getElementById('validate').onclick = checkFilled;
}

function checkFilled() {
    var input = document.getElementByID('myText');
    if(input.value == '')
    {
        input.style.background = 'red';
    }
    else
    {
        input.style.background = '';
    }
}   

但是这是不允许的,因为我已经为每个输入框添加了ID。我也尝试过使用document.querySelectorAll。但它无法奏效。我做错了什么吗?

请帮我这个&gt;。&lt;感谢你们!干杯;)

2 个答案:

答案 0 :(得分:0)

试试这个

$(document).ready(function () {
    $('#validate').click(function (e) {
        $('input').each(function () {
            if ($(this).val() == '') $(this).css('background-color', 'red')
        });

    });
});

DEMO

JS解决方案

在HTML <button id="validate" onclick="checkFilled() ">validate</button>

function checkFilled() {
    var input = document.querySelectorAll('input')
    for (var i = 0;i < input.length; i++) {
    if (input[i].value == '') {
        input[i].style.background = 'red';
    } 
    }
}

DEMO

答案 1 :(得分:0)

见这个

$(document).ready(function () {
    $('#validate').click(function (e) {
        $("#formtovalidate").find("input").each(function() {
            var input = $(this);
            if (input.val() == "") {
                input.css("background-color", "red");
            }
        });
    });
});