我有一个小问题要问。如果在点击“验证”按钮后它们保持为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;感谢你们!干杯;)
答案 0 :(得分:0)
试试这个
$(document).ready(function () {
$('#validate').click(function (e) {
$('input').each(function () {
if ($(this).val() == '') $(this).css('background-color', 'red')
});
});
});
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';
}
}
}
答案 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");
}
});
});
});