Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 945
anmarti Avatar asked Jan 15 '23 22:01

anmarti


1 Answers

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.

like image 160
Alnitak Avatar answered Feb 17 '23 10:02

Alnitak