1

I've a group of inputs like <input type="text" name="clients[]" /> that are loaded via AJAX. Before the user submits the form, I need to check if at least one of them has been filled. I don't know how to do this if is an array.

Thank you in advance!

2 Answers 2

3

Bind a function to the submit event for the form like this:

// assuming #foo is the form and each grouped element has classname bar
// also, this assumes that your form is not loaded by AJAX, but only the elements
// contained in it
$('#foo').submit(function() {
    var elements = $("input[name='clients[]']");
    var validated = false;
    elements.each(function() {
        if ($(this).val() != '') {
            validated = true;
            return false; // will break the each
        } else {
            validated = false;
        }
    });
    return validated;
});

Live example here.

Sign up to request clarification or add additional context in comments.

2 Comments

are you NOT forgetting a .live function due to ajax returned strings?
No. the elements are bound after the form is submitted, so live() would not be needed in this case.
0

Like this:

var $filledTextboxes = $(":text[name='clients[]']").filter(function(){
   return $.trim($(this).val()) != "";
});
if($filledTextboxes.size() == 0)
   alert("All are empty");
else
   alert("Not all are empty");

Hope this helps. Cheers

1 Comment

Thank you Edgar. This will work with loaded via ajax inputs? Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.