I want to check some fields values in a form against an existing object's values. If the values match, change a class value (it will add a sign). The following code is working, but I would like to know if it can be improved.
Preset obj:
var obj = {
preset_a:{
input:{
field_a:"value",
...
field_b:"value",
},
select:{
...
},
radio:{
...
}
},
preset_b:{
input:{
field_a:"value",
...
field_b:"value",
},
select:{
...
},
radio:{
...
}
}
};
The script:
$(document).ready(function(){
for (var preset in obj){
$.each(obj[preset], function(type){
var flag = true;
$.each(obj[preset][type], function(k, v){
if (type == 'radio'){
flag = ((v) == $('#' + k + ' > input[type="radio"]:checked').val());
} else {
flag = ((v) == $(type + '#' + k).val());
}
if (flag == false){
return false;
}
});
if (flag == false){
$(preset + ' i#id').attr('class', 'radio-unchecked');
return false;
} else {
$(preset + ' i#id').attr('class', 'radio-checked on');
}
});
}
});
1 Answer 1
Inside one of the $.each
calls, you could simplify this part:
if (flag == false){ return false; }
to this:
return flag;
When the value is true
, $.each
will continue normally, and stop after it is false
, so the behavior remains the same.
Instead of:
if (flag == false) {
It's more common to write:
if (! flag) {
For simplicity, it might be a good idea to flip the condition:
if (flag) {
$(preset + ' i#id').attr('class', 'radio-checked on');
} else {
$(preset + ' i#id').attr('class', 'radio-unchecked');
return false;
}
And to reduce code duplication, I would extract the dom lookup that is common in both branches of the if-else:
var preset = $(preset + ' i#id');
if (flag) {
preset.attr('class', 'radio-checked on');
} else {
preset.attr('class', 'radio-unchecked');
return false;
}
The two innermost loops use $.each
,
but the outer loop is a traditional for
.
For the sake of consistency, it might be good to use $.each
for all.
-
\$\begingroup\$ Thank you very very much for your tips and explanations. Could you be so kind to take a look [codereview.stackexchange.com/questions/95959/… that is more or less related. \$\endgroup\$n.h.– n.h.2015年07月11日 22:27:41 +00:00Commented Jul 11, 2015 at 22:27