Use underscore.js list functions to collect jquery objects

I am working with an application that uses both jQuery and underscore.js. I would like to be able to use some underscore iterator functions such as any() and all() over a collection of jQuery objects. Is there any way to do this? I would like to do something similar to the following:

 checkboxes = $("input[type=checkbox]"); _.filter(checkboxes, function(box) { return box.is(":checked"); }); 

but this causes an error:

 Uncaught TypeError: Object #<HTMLInputElement> has no method 'is' 

therefore, I assume that the field in this context does not act as a jQuery object.

+6
source share
2 answers

You should wrap box in jQuery:

 checkboxes = $("input[type=checkbox]"); checkboxes = _.filter(checkboxes, function(box) { return $(box).is(":checked"); }); 

In addition, instead of creating a new object for each individual item in the collection, you can simply use your own box.checked :

 checkboxes = $("input[type=checkbox]"); checkboxes = _.filter(checkboxes, function(box) { return box.checked; }); 

On the side of the note: jQuery has its own filtering method :

 checkboxes = $("input[type=checkbox]").filter(function() { return $(this).is(":checked"); }); 

Also, in your example - are you sure you need to filter? You can just as easily use this as your selector:

 checkboxes = $("input[type=checkbox]:checked") 
+13
source

Here box is an object of type HTMLInputElement . This is not a jQuery object. Since .is is a jQuery object object, you need a jQuery object from box .

This can be done, $(box) . Then apply .is() .

 $(box).is(":checked"); 
+1
source

Source: https://habr.com/ru/post/905656/


All Articles