Question

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.

Was it helpful?

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.

OTHER TIPS

You could store the ID on the element itself (using jQuery's data method) when you do the filter, and then retrieve that value in the click handler.

$jq("button").filter(function(){
    var $this = $jq(this);
    var matches = $this.attr('id').match(/^user_(\d+)_edit$/);

    if (matches) {
        $this.data('idNumber', matches[1]);
    }

    return matches;
}).click(function(){
    var user_id = $(this).data('idNumber');

    alert('click on user edit button with ID ' + user_id);
});

Personally, I would preprocess the DOM:

$(function() {

$("button").each(function() { 
      var matches = $(this).attr("id").match(/^user_(\d+)_edit$/);

      if (matches) {
         $(this).data("user_edit_id",matches[1]);
      }
   }
});

Then you can simply:

$("button").filter(function(){
    return $(this).data("user_edit_id");
}).click(function(){
    var user_id = $(this).data("user_edit_id");

    alert('click on user edit button with ID ' + user_id);
});

It's not a perfect solution to what you want, but it's one way...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top