Mauricio
Mauricio

Reputation: 1711

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

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?

Upvotes: 3

Views: 3641

Answers (3)

David Tang
David Tang

Reputation: 93664

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! */ }

Upvotes: 6

mcgrailm
mcgrailm

Reputation: 17640

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

Upvotes: 0

user342706
user342706

Reputation:

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" />

Upvotes: 4

Related Questions