我有两个具有相同类名的元素,我用$(“。text-input”)
来选择它们。 在on输入回调中,
$(".text-input").on("input", function (event) {
console.log(is any of those not empty?);
})
在其中任何一个中,我想知道是否至少有一个输入框不是空的。 我该怎么做?
实际上,在测试之前,您应该始终.trim()
内容。
您不希望空格说明有效的输入值:
null
$(".text-input").on("input", function() {
const is_empty = !this.value.trim();
if (is_empty) console.log("field is empty");
$(this).toggleClass("is-empty", is_empty);
});
/* bool helpers */
.is-empty {
outline: 2px solid red;
outline-offset: -2px;
}
<input type="text" class="text-input">
<input type="text" class="text-input">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
您可以使用eace()
方法检查所有text-input
元素的内容。 使用Not(this)
,可以将当前键入的文本框排除在外。
null
$('.text-input').on('input change', function() {
// check all elements with the 'text-input class', but exclude the one currrently typed into
$('.text-input').not(this).each(function(){
// if there is content in one of the others, then display a message in console
if($(this).val().trim().length > 0) {
// one of the inputs already has something in it
console.log('Something is filled in another box');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="text-input" />
<input type="text" class="text-input" />
<input type="text" class="text-input" />
一种方法是使用filter()
创建一个包含值的集合,然后将该集合的长度与所有输入的长度进行比较
null
const $inputs = $('.text-input').on('input', function() {
const $filled = $inputs.filter((_, el) => !!el.value.trim());
console.clear();
if ( $filled.length < $inputs.length ) {
console.log('At least one is empty')
} else {
console.log('No empties')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="text-input" />
<input type="text" class="text-input" />
<input type="text" class="text-input" />