Max Williams
Max Williams

Reputation: 32943

Can't call .join() on the values of some elements

I've got a variable selectedTagNames which I set thus:

var selectedTagNames = $(".js-tag-name:checked").map(function(){return $(this).val()});

selectedTagNames
=> ["song:age_suitability=11-13", "song:age_suitability=5-7"]

It appears to be an array. I want to join the values into a single string with '||', but I can't:

var searchTerm = selectedTagNames.join('||')
=> VM7234:2 Uncaught TypeError: undefined is not a function
message:  "undefined is not a function"
stack: (...)get stack: function () { [native code] }
set stack: function () { [native code] }__proto__: Error

I can do it manually, rather than using the variable:

["song:age_suitability=11-13", "song:age_suitability=5-7"].join('||')
=> "song:age_suitability=11-13||song:age_suitability=5-7"

So, the value of that variable must be something different to the array that I use in the second example, even though it appears to be the same. They both just return 'object' for typeof().

I'm using jquery version 1.7.1.

Can anyone tell me a) what's going on here? b) how to gather the values of the selected checkboxes into an array, so I can see how many there are, and join them together, avoiding whatever's going wrong here?

Upvotes: 0

Views: 57

Answers (2)

Barmar
Barmar

Reputation: 781096

.map() returns a jQuery collection, not an array. You can convert this to an array by calling .get() on the result.

var selectedTagNames = $(".js-tag-name:checked").map(function(){
    return $(this).val()
}).get();

Upvotes: 1

Mitya
Mitya

Reputation: 34556

$(selector).map() returns an array-like object akin to what jQuery returns from a selector.

You need the static method instead:

$.map($('.js-tag-name:checked'), function(el) {
    return $(el).val();
});

Upvotes: 1

Related Questions