Jay
Jay

Reputation: 3393

How to Bind keyup event to jQuery plugin

i am trying to create jQuery plugin which needs to trigger on keyup of input tag. But, somehow its not working :(

I've tried it so far:

JS:

$.fn.search_panel = function() {
    if($(this).prop("tagName").toLowerCase() == 'input'){
        var input_str = $.trim($(this).val());
        console.log($(this));

        onkeyup = function(){
            console.log(input_str);
        }
    }
};

Plugin Initialization

$(document).ready(function(){
    $('input').search_panel();
});

HTML:

<input type="text" />

From the above code, it only console when page loads for the first time, but after entering anything in input box it doesn't console.

Upvotes: 0

Views: 1779

Answers (2)

Shaunak D
Shaunak D

Reputation: 20636

Add keyup event inside plugin and bind it to current input,

$.fn.search_panel = function () {
    if ($(this).prop("tagName").toLowerCase() == 'input') {
         $(this).keyup(function () {
            var input_str = $.trim($(this).val());
            console.log($(this));
            console.log(input_str);
         });
    }  
};

Demo

Upvotes: 1

CodingIntrigue
CodingIntrigue

Reputation: 78535

You're inadvertantly binding to the window's onkeyup event. You should use $(this).on instead to bind to the individual keyup event on each input:

$.fn.search_panel = function() {
    // Iterate all elements the selector applies to
    this.each(function() {
        var $input = $(this);
        // Can probably make this more obvious by using "is"
        if($input.is("input")){
            // Now bind to the keyup event of this individual input
            $input.on("keyup", function(){
                // Make sure to read the value in here, so you get the
                // updated value each time
                var input_str = $.trim($input.val());
                console.log(input_str);
            });
        }
    });
};
$('input').search_panel();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input><input><input><input>

Upvotes: 3

Related Questions