How apply custom jQuery functions to selectors that match > 1 elements

javascript, jquery

Solution

In your case you can just use `this` - it's already a jQuery object matching each of the supplied elements:

jQuery.fn.setReadOnly = function() {
    return this.prop('readonly', true).css('background-color', '#f0f0f0');
}

In the more general case where you want to do something explicitly on each DOM element other than call a jQuery function on the entire collection you would do this:

jQuery.fn.myFunc = function() {
     return this.each(function() {
         ...
     });
});

That's unnecessary in your particular case because the `.prop` and `.css` calls perform the `.each` implicitly.

Problem

I have several textboxes that I want to apply a custom jquery function: ``` jQuery.fn.setReadOnly = function () { var o = $(this[0]); o.prop('readonly', true) .css('background-color', '#F0F0F0'); }; ``` Now I need to do: ``` $('#txt1').setReadOnly(); $('#txt2').setReadOnly(); $('#txt3').setReadOnly(); $('#txt4').setReadOnly(); $('#txt5').setReadOnly(); ``` I want to achieve the following: ``` $('#txt1, #txt2, #txt3, #txt4, #txt5').setReadOnly(); ``` Thank you.

Original source