ale
ale

Reputation: 11830

Calling jquery function with a parameter when needed i.e. not on page load

A very basic question...

I have a jquery function that fires on page load:

$(document).ready(function () {
   // some code
   $('#filter').keyup(function() {

   });
}

The code filters the first column in a HTML table. I now want to filter by the nth column but I don't want to write two very similar functions.

I can change the function to accept a single argument like so:

$(document).ready(function (column_num) {
   // some code
   $('#filter').keyup(function() {

   });
}

which is fine. However, how do I execute the function in my HTML file giving the function a single argument?

Upvotes: 0

Views: 202

Answers (2)

user920041
user920041

Reputation:

HTML:

Filter 1:<input type="text" class="filter" data-filter-column="1">
Filter 2:<input type="text" class="filter" data-filter-column="2">
Filter 3:<input type="text" class="filter" data-filter-column="3">

<div id="test"></div>

JavaScript:

$(document).ready(function () {
   $('.filter').keyup(function(e) {
       var column_num = $(this).attr("data-filter-column");
       var filter_token = $(this).val();
       //filterCol(column_num, filter_token); 
       $("#test").text("Filter column " + column_num + " by token " + filter_token);
   });
});

See demo here: http://jsfiddle.net/3cte4/2/

Upvotes: 2

lalibi
lalibi

Reputation: 3088

I am not entirely sure I've understand what you are trying to accomplish but I think you need something like this:

var handler = function(column_num) {
    switch (column_num) {
        ...
    }
}

$(document).ready(function () {
    $('#filter_for_column_1').keyup("column1", handler);
    $('#filter_for_column_2').keyup("column2", handler);
    $('#filter_for_column_3').keyup("column3", handler);
    ...
}

Upvotes: 1

Related Questions