Iain Simpson
Iain Simpson

Reputation: 469

Add a second function to this jquery?

The following jQuery function filters my table columns by letter. There is an <a> for each letter. I'm not sure how to add another function though to filter column 1 using a different dropdown on the html side.

JavaScript:

function fil(rexp)
{
    $('#tablestyle').dataTable().fnFilter(rexp, 0, true, false);
}

HTML:

<div style="float:left;" class="sortalpha">
    <a href="javascript:fil('');">ALL</a>
    | <a href="javascript:fil2('^a');">A</a>
    | <a href="javascript:fil('^b');">B</a>
    <!-- [...] -->
    | <a href="javascript:fil('^z');">Z</a>
</div>

What I have tried to do is copy the top part and change fil to fil2 then copy the HTML part and change those to fil2. Is that the correct way?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Just to give everyone a bit more info, I am using datatables {www.datatables.net} which is a jquery script that presents tables in a nice looking ui with various differnt functions to it like search, filter records per page etc. I have implemented this mod that someone has listed here >> http://www.datatables.net/forums/discussion/6641/filtering-with-first-letter/p1

It works fine and when I select each letter it filters column 0 using whatever letter I have clicked on. What I am trying to do is have two different filters, one to filter column 0 which is the name of the person, and also another filter that does exaclty the same thing, but for column 1 which is business name, I just wasnt sure how to add the same piece of code twice?.

Upvotes: 1

Views: 253

Answers (2)

Peter-Paul van Gemerden
Peter-Paul van Gemerden

Reputation: 7011

I don't really know your context, but I would suggest you try using event handlers instead of JavaScript URLs.

So instead of this:

<a href="javascript:fil('');">ALL</a>

You could do this:

$('.sortalpha a').on('click', function() {
    fil('');
});

Of course, this would make all links filter on ''. To fix that, you could get the text from the <a> that was clicked and use that to call fil(), like so:

function fil(rexp) {
    if (rexp.length > 0) {
        rexp = '^' + rexp;
    } 
    //$('#tablestyle').dataTable().fnFilter(rexp, 0, true, false);
    alert('Filter on: "' + rexp + '"');
}

$('.sortalpha a').on('click', function(event) {

    var letter = $(this).text().toLowerCase();

    if (letter === 'all') {
        fil('');
    } else {
        fil(letter);
    }
});

Here's a working example: http://jsfiddle.net/uzGat/2/

Edit: I updated the answer to account for capital letter and the ^ in the regular expressions.

Upvotes: 1

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34150

if the plugin is well written, it must maintain chainbilty so you can do like:

function fil(rexp)
{
$('#tablestyle').dataTable().fnFilter(rexp, 0, true, false).fnFilter(rexp2, 0, true, false);
}

Upvotes: 1

Related Questions