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.
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?
You could replace that function with:
function checkingFieldsArentEmpty(){
return !(allFields.filter(":input[value]").length != allFields.filter(":input").length);
}
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.
hasEmptyFields = !!$.grep(allFields, function(a) { return a.val() === null; }).length
精彩评论