May 15, 2012

Redraw table if search bar is empty

Question by Tural Teyyuboglu

Based on this discussion, added code below into my JS code to enable filtration to be triggered by pressing the enter key instead of keyup or delay.

jQuery.fn.dataTableExt.oApi.fnSetFilteringPressEnter = function (oSettings) {
    var _that = this;

    this.each(function (i) {
        $.fn.dataTableExt.iApiIndex = i;
        var $this = this;
        var anControl = $('input', _that.fnSettings().aanFeatures.f);
        anControl.unbind('keyup').bind('keypress', function (e) {
            if (e.which == 13) {
                $.fn.dataTableExt.iApiIndex = i;
                _that.fnFilter(anControl.val());
            }
        });
        return this;
    });
    return this;
}

/* Example call */
$(document).ready(function() {
    $('.dataTable').dataTable().fnSetFilteringPressEnter();
} );

Now what I want to do is, when user removes keyword from search bar, I want to redraw table. Currently it doesn’t redraw without pressing enter button. How can I achieve this result?

Answer by Starx

I think its safe to do on the keyup event of keyboard, unlike only triggering on the enter key press.

anControl.off('keyup').on('keypress', function (e) {
        $.fn.dataTableExt.iApiIndex = i;
        _that.fnFilter(anControl.val());
});

Also, note I have used on() and off() for delegation instead of bind and unbind which are deprecated as of jQuery 1.7

Or, you can create a completely different handler for the specific case, where all the keywords are deleted on the text box.

    anControl.off('keyup').on('keypress', function (e) {
        if (e.which == 13) {
            $.fn.dataTableExt.iApiIndex = i;
            _that.fnFilter(anControl.val());
        }
        if(anControl.val().length == 0) {
               //redraw table
        }

    });

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!