Skip to content Skip to sidebar Skip to footer

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('backgro

Solution 1:

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

jQuery.fn.setReadOnly = function() {
    returnthis.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() {
     returnthis.each(function() {
         ...
     });
});

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

Solution 2:

You're currently setting explicitly $(this[0]), which only accesses the first element.

You want to use o = $(this);

Demo

Edit: as Alnitak points out, this will be a jQuery collection, and you could go right ahead to do this.prop(...) without the extra $() wrapping.

Solution 3:

Normally, the syntax for applying it to all matched elements is something like this:

jQuery.fn.setReadOnly = function () {
    returnthis.each(function () {
        $(this).prop("readonly", true).css("background-color", "F0F0F0");
    });
};

While it's not necessary to use the .each method on this to iterate through every matched item, it would be the correct way to use if you ever expanded this plugin to do more and needed to apply things to each element outside of jQuery methods (the prop and css parts).

Solution 4:

See my upvote: use the this.each - it's better and returns for object chaining.

The 'this' object you're grabbing the first item out of - simply loop that with a:

for(var i = 0, len = this.length; i<len; i++){
    var o = $(this[i]);
    o.prop('readonly', true)
    .css('background-color', '#F0F0F0');
}

Untested, but i"m pretty sure that works.

Solution 5:

This is how you'd write it

Don't forget to chain.

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

Post a Comment for "How Apply Custom Jquery Functions To Selectors That Match > 1 Elements"