user1372430
user1372430

Reputation:

Create jQuery plugins including keyup function

I have a jQuery function filtering labels like this:

$.filtrele = function(e) {
    var value = $(e).val().toLowerCase();
    var li = $("#dgg > label");
    li.hide();
    li.filter(function() {return $(this).text().toLowerCase().indexOf(value) > -1;}).show();
}

I use it like this:

$('#filt').keyup(function() {
    $.filtrele(this);
});

I want to combine these and use like this: $('#filt').filtrele(); I tried some combinations like this:

$.fn.filtrele= function(){
    $(this).keyup(function()
    {
        var value = $(this).val().toLowerCase();
        var li = $("#dgg > label");
        li.hide();
        li.filter(function() {return $(this).text().toLowerCase().indexOf(value) > -1;}).show();
    });
};

But I did not manage it.

Upvotes: 0

Views: 44

Answers (2)

adricadar
adricadar

Reputation: 10209

You have to call like this this.keyup not $(this).keyup, "This is because our filtrele function is a part of the same object as .keyup()."

$.fn.filtrele= function(){
    this.keyup(function()
    {
        var value = $(this).val().toLowerCase();
        alert(value);
        var li = $("#dgg > label");
        li.hide();
        li.filter(function() {return $(this).text().toLowerCase().indexOf(value) > -1;}).show();
    });
};

$('#filt').filtrele();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="filt" />

Upvotes: 2

DGS
DGS

Reputation: 6025

Try changing your $(this).keyup(function() to this.keyup(function() per https://learn.jquery.com/plugins/basic-plugin-creation/

$.fn.filtrele= function(){
    this.keyup(function()
    {
        var value = $(this).val().toLowerCase();
        var li = $("#dgg > label");
        li.hide();
        li.filter(function() {return $(this).text().toLowerCase().indexOf(value) > -1;}).show();
    });
};

Upvotes: 2

Related Questions