检查所有输入字段是否已用jQuery填写 [英] Check all input fields have been filled out with jQuery

查看:141
本文介绍了检查所有输入字段是否已用jQuery填写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个div,每个div都有一个dfew输入字段和下一个按钮。
我想编写一个jQuery片段,当单击下一个按钮时,它会检查以确保所有输入字段与按钮相同的div不是空的。

I have 3 divs, each with a dfew input fields and next button on. I want to write a snippet of jQuery that when the next button is clicked it checks to ensure all input fields WITHIN the same div as the button, are not null.

我尝试过以下但没有运气,但我100%肯定是错的,只是我无法在网上找到相关信息...

I've tried the following with no luck but Im 100% certain its wrong, only I cant find the relevant information online...

http://jsfiddle.net/xG2KS/1/

推荐答案

您可以使用 过滤器 将所有输入元素的集合减少到仅为空的元素,并检查剩余的 length 属性:

You could use filter to reduce the set of all input elements to only those that are empty, and check the length property of what remains:

$(".next").click(function() {
    var empty = $(this).parent().find("input").filter(function() {
        return this.value === "";
    });
    if(empty.length) {
        //At least one input is empty
    }
});

请注意,上面代码中的empty定义是空字符串。如果您想将空格也视为空,您可能希望在比较之前修剪该值。

Note that the definition of empty in the above code is an empty string. If you want to treat blank spaces as empty too, you may want to trim the value before comparing.

另请注意,无需传递这个进入过滤器函数内的jQuery。 DOM元素本身将具有属性,并且访问它的速度要快得多,而不是使用 val

Also note that there is no need to pass this into jQuery inside the filter function. The DOM element itself will have a value property, and it's much faster to access that instead of using val.

这是一个更新的小提琴

这篇关于检查所有输入字段是否已用jQuery填写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆