tags:

views:

73

answers:

4

Hi.

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.

+2  A: 

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?

cletus
a jQuery object
Felix Guerrero
+1  A: 

You could replace that function with:

function checkingFieldsArentEmpty(){
    return !(allFields.filter(":input[value]").length != allFields.filter(":input").length);
}
karim79
I got <select> values too.
Felix Guerrero
@Felix Guerrero: From the [documentation](http://api.jquery.com/input-selector/): *Selects all input, textarea, select and button elements.*
Felix Kling
@Felix Guerrero - I don't understand, the function in your post applies to all the elements contained within `allFields`.
karim79
@karim79: **I** *think* that the **other** Felix thinks that `:input` only applies to `<input>` elements.
Felix Kling
+1  A: 

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.

Felix Kling
A: 

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

x1a4