Felix
Felix

Reputation: 3134

Checking values in this array, JQuery

I have this array (JQuery) where I add all my form's controls, it looks like:

var     name       = $("#name"),
        surname    = $("#surname"),
        address    = $("#address"),
        phone      = $("#phone"),
        photo      = $("#photo"),
        grade      = $("#grade"),
        profession = $("#profession"),
        email      = $('#email'),
        title      = $('#title'),

                    allFields =    $([]).add(name)
                                        .add(surname)
                                        .add(address)
                                        .add(phone)
                                        .add(photo)
                                        .add(grade)
                                        .add(profession)
                                        .add(email)
                                        .add(title)
                                        .add(grade);

I want to check the values of each element into the 'allFields' array with

function checkingFieldsArentEmpty(){

              for (var f in allFields){
                    if(f.val() === null)
                        //if any val is null just return false
                        return false;
                }
                return true;
            }

I need ideas in order to improve the last function. Thanks.

Upvotes: 1

Views: 2204

Answers (4)

x1a4
x1a4

Reputation: 19485

hasEmptyFields = !!$.grep(allFields, function(a) { return a.val() === null; }).length

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816442

You could use .reduce():

function checkingFieldsArentEmpty(){
    return allFields.reduce(function(prev, curr, index, array) {
        // for checking for emptiness just add  && cur.val() !== "" 
        return prev && curr.val() !== null; 

    }, true);
}

Btw. using jQuery to create and populate the array seems unnecessary to me.

Upvotes: 1

cletus
cletus

Reputation: 625087

Try:

var names = ["name", "surname", "address", "phone", "photo",
  "grade", "profession", "title"];
var allFields = {}
$.each(names, function(i, name) {
  allFields[name] = $("#" + name).val();
});

and then you can do:

if (allFields.name) { // true if it has a value, false for ""
  ...
}

The way you're doing it is a little convoluted. Do you want an array or a jQuery object?

Upvotes: 2

karim79
karim79

Reputation: 342635

You could replace that function with:

function checkingFieldsArentEmpty(){
    return !(allFields.filter(":input[value]").length != allFields.filter(":input").length);
}

Upvotes: 1

Related Questions