Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array with jQuery of object IDs to process on Django backend

I've got some javascript that is creating an li based on an object returned from the backend after an AJAX search. The user can keep searching for devices and when selected they are added to the current page (as an li). Each time a new li is created, I want to send the id's of the objects that have already been chosen.

When the li's are created, their id's are named "device-###" where ### is the ID of the device in the database, so I need to strip that part out.

Here's the javascript that's giving me problems:

        var children = $('#temp_inventory').children();
        var count = children.length;
        var devices = [];
        var i = 0;
        while (i<=count){
            devices[i] = children[i].id.substr(4);
            i++;
        };

I get the following error:

Uncaught TypeError: Object #<HTMLLIElement> has no method 'attr'

I also tried it the non-jQuery way:

devices[i] = children[i].id.substr(4);

And I end up with this error:

Uncaught TypeError: Cannot read property 'id' of undefined

When I throw in alert(children[i].id.substr(4)); I get an alert with the number I'm expecting.

like image 787
gohnjanotis Avatar asked Feb 10 '11 22:02

gohnjanotis


2 Answers

Part of the issue is probably that your loop uses <= instead of <. Remember the last item in a list that uses a zero-based index is length - 1.

To create an Array of the IDs, you could use the map()(docs) method instead.

var devices = $('#temp_inventory').children().map(function() {
    return this.id.substr(4);
}).get();

The .map() method populates a jQuery object (which is an Array-like object) with the values you return in the function.

Then the get()(docs) method gives you an Array of those values instead of a jQuery object.

You could also use the toArray()(docs) method which does the same thing.

var devices = $('#temp_inventory').children().map(function() {
    return this.id.substr(4);
}).toArray();
like image 150
user113716 Avatar answered Oct 21 '22 21:10

user113716


I think you may want,

while (i<count){
  devices[i] = children[i].id.substr(4);
  i++;
};

otherwise the last iteration will be beyond the last item in the array.

A more concise way of doing this using $.map()

var devices = $.map($('#temp_inventory').children(), function(elem) {
  return elem.id.substr(4);   
});
like image 30
Russ Cam Avatar answered Oct 21 '22 22:10

Russ Cam