Reputation: 318
Here's what I'm trying to do: Currentrly i have a list of tags, which will sort some data from database on click, is there a way to get a list of elements which are choosed?
<a href="javascript:;" class="tag tagId_4">Tag 4</a>
<a href="javascript:;" class="tag tagId_3">Tag 3</a>
<a href="javascript:;" class="tag tagId_2">Tag 2</a>
<a href="javascript:;" class="tag tagId_1">Tag 1</a>
And here is what have done at this moment:
$('.tag').click(function(){
var id = $(this).attr('class');
id = id.substr(10);
$(this).addClass('tag_selected');
});
How can i get a list of id's of all links with class tag_selected?
Upvotes: 0
Views: 86
Reputation: 4612
The jQuery selector $()
will return an array of elements if the query matches more than one element, so:
$('.tag_selected');
will return them all.
In terms of the design of your implementation, I'd switch to using the actual id attribute of the <a>
tag to store the id of the element.
You can use something like this to retrieve the id
number of each selected element to an array:
var ids = $('.tag_selected').map(function() {
return $(this).attr('id').match(/.+_(.+)/)[1];
}).get();
That regular expression will basically match anything up until an underscore, then capture anything after the underscore and return it. The [1]
at the end is accessing the second item in the array returned from the match
function (which is the first captured string).
Upvotes: 1
Reputation: 6577
I believe by using "$(.tag-selected).each(someFunction)" and let the function do something for an individual element containing that class.
Upvotes: 0
Reputation: 368
function getListOfSelectedElements() {
var list = [];
$(".tag_selected").each(function (index, element) {
var id = $(element).attr("id");
if (id) {
list.push(id);
}
});
return list;
}
Upvotes: 1