jQuery filter through IDs and then capture matches
css-selectors, jquery, pattern-matching
Solution
How about avoiding the first match?
$jq("button[id^=user][id$=edit]").click(function() {
});
Would select all buttons that have an ID that starts with user and ends with edit.
Although honestly, looking at your use case, it would be WAY better to simply give all buttons that are meant to edit a user a class of "edit_user" and then just do:
$jq('button.edit_user').click(function() {
});
It is cleaner, faster, and the jQuery way of getting all elements that serve a similar purpose.
As far as getting the user id there's been some lively discussion on custom attributes on this site (Custom attributes - Yay or nay?) and I personally do `data-userid='5'` in my elements and then just do `var id = $(this).attr('data-userid');` to get the ID. Nice and easy. Won't validate as XHTML, though.
Problem
I find myself doing this repeatedy. ``` $jq("button").filter(function(){ return this.id.match(/^user_(\d+)_edit$/); }).click(function(){ var matches = this.id.match(/^user_(\d+)_edit$/); var user_id = matches[1]; alert('click on user edit button with ID ' + user_id); }); ``` So I want to apply a click event to some buttons and in the click event handler I need the user ID. Is there a way I can avoid the second match? ``` $jq("button").filter(function(){ return this.id.match(/^user_(\d+)_edit$/); }).click(function(){ var user_id = some_magic_variable; alert('click on user edit button with ID ' + user_id); }); ``` Thanks.