views:

41

answers:

2

What is wrong with this code...

var objects = $(".validated").filter(function(){
                                   return $(this).attr("name") == 'name';
                             }).filter(function (){
                                   return $(this).val() == '';
                             });

Its really bugging me :(

A: 

Filter will remove an element when the function returns false. So you want it to return false when you encounter an element with name="name" and when it is empty.

var objects = $(".validated").filter(function(){
                                   // Will return false when name="name"
                                   return $(this).attr("name") != 'name';
                             }).filter(function (){
                                   // Will return false when the value is blank
                                   // Added trim to ensure that blank spaces
                                   // are interpreted as a blank value
                                   return $.trim($(this).val()) != '';
                             });

A shortened version would be:

var objects = $(".validated").filter(function(){
                  // Will return false when name="name" or blank value
                  return $(this).attr("name") != 'name' && $.trim($(this).val()) != '';
              });
a432511
so the 'name' bit - will it add the object to the array 'objects' when its got the attr 'name'='name' ??
tarnfeld
no... it gets rid of elements that have name="name"
a432511
and also gets rid of elements with a blank value
a432511
+1  A: 
var objects = $(".validated").filter(function() {
    var ele = $(this);
    return ele.attr("name") == 'name' || ele.val() == '';
});
jitter
I can't believe this was accepted. It doesnt achieve what tarnfeld asked for... He wants to filter OUT when name='name' and the element value is blank. Filter eliminates elements when the function returns false. "If the function returns false, then the element is removed - anything else and the element is kept in the resulting set of matched elements." -http://docs.jquery.com/Traversing/filter
a432511
It was not all that clear to me if he really wanted to do what you imply. His own code seemed to try to keep exactly those elements which mine does. You where the first yourself to use the word "filter out". Maybe tarnfeld understood by "out" "filter them out == remove the others" e.g. to add a error class to those or similar
jitter