[英]Jquery - How to check if all inputs in a div are not empty?
寻找一种简单的方法来验证所有必需的输入,在某个div中。 换句话说,确保某个div中的所有必需输入都不为空。
此处的以下代码显示了一种检查所有输入并确保它们在给定页面上不为空(包括仅包含空格的输入)的方法。
我想做同样的事情。 只是在一个特定的div和所有必需的输入。
$("input").filter(function () {
return $.trim($(this).val()).length == 0
}).length == 0;
您可以执行相同的操作,但是您应该更改选择器以仅定位给定div中的输入并添加[required]
选择器以仅选择具有required
属性的那些:
$("div_selector input[required]").filter(function () {
return $.trim($(this).val()).length == 0
}).length == 0;
希望这可以帮助。
$('button').on('click',function(){ var result = $("#div_selector input[required]").filter(function () { return $.trim($(this).val()).length == 0 }).length == 0; console.log(result); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name='first' required> Required input out of the div <div id='div_selector'> <input name='second' required> Required input <br> <input name='Third'> <br> <input name='Fourth' required> Required input </div> <br> <button>Check</button>
这是一个使用Array.reduce()
的简单Array.reduce()
:
$(".your-div input").reduce((allFilled, input) =>
allFilled && $.trim($(input).val()) !== "", true)
这种方法将匹配输入,选择,textarea等任何输入
var canSubmit = true;
$.each($('.div-in-question').find(':input'), function(element, index){
canSubmit = canSubmit && ($(element).val() !== '');
});
// at this point canSubmit will be true or false and you can act upon it
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.