开发者

jQuery: How to determine if one or more textboxes are empty

开发者 https://www.devze.com 2023-02-22 05:33 出处:网络
Suppose I\'ve got a set of textboxes of the form: <input class=\"member\" type=\"text\" name=\"integrantes[]\" />

Suppose I've got a set of textboxes of the form:

<input class="member" type="text" name="integrantes[]" />

For validation, I need to make sure all of these textboxes contain a value, and display an error if not.

开发者_运维知识库

My current idea is basically to set the value outside, a la:

var oneEmpty = false;
$(".member").each(function() { oneEmpty = oneEmpty || $(this).val() == "" });
if (oneEmpty) { etc }

However, it's not particularly elegant. Therefore, is there a better way to pull it off?


You can simply filter out all the inputs that are not empty, and check if you have any inputs left:

var empties = $('.member').filter(function () {
    return $.trim($(this).val()) == '';
});
if (empties.length) { /* Error! */ }


If you are using jquery validation you could just put a required class on your textbox input and it would validate for you. jQuery Validate

<input class="member" type="text" name="integrantes[]" class="required" />


Kyte I would recommend you use jQuery validate and apply a required class on all text inputs I also I imagine that you may want it for other stuff too

0

精彩评论

暂无评论...
验证码 换一张
取 消