1

I have read a lot about this issue in many threads. The best I have found is here: jQuery's .click - pass parameters to user function

 // say your selector and click handler looks something like this...
 $("some selector").click({param1: "Hello", param2: "World"}, cool_function);

 // in your function, just grab the event object and go crazy...
 function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);
 }

My problem is that I want to assign dynamically values for my parameters. Not just "Hello" etc.

For example I have something like this:

   <?php
   for($i=0;$i<5;$i++){
   ?>
   <input type="text" id="client_<?=$i?>"> 
   <?
   }
  ?>

How can I rewrite jQuery to handle different values for parameters? For example 0,1,2,3,4

Obviously, I can't do something like

 $("#client_1").click({num:1}, cool_function);
 $("#client_2").click({num:2}, cool_function);
 $("#client_3").click({num:3}, cool_function); 

etc.

Community
  • 1
  • 1
  • You first posted a clear cut question, which I answered. Then you pretty much changed the original question. Why not think first about what you're actually trying to do, then ask? HTML data attributes are the way to go in your (updated) use case. – Marc Diethelm Jan 21 '13 at 09:26
  • Just tried to make it more clear. Yes, data attributes thanks –  Jan 21 '13 at 10:23

2 Answers2

1

In that specific example, you're probably best off just grabbing the id, since you're already outputting it to the element:

$("some selector").click(function() {
    var num = parseInt(this.id.replace(/\D/g, ""), 10);
    // Do something with `num`
});

If you weren't already putting an id there, you could use a data-* attribute:

<?php
for($i=0;$i<5;$i++){
?>
<input type="text" data-num="<?=$i?>"> 
<?
}
?>

...and then retrieve it in the click handler:

$("some selector").click(function() {
    var num = parseInt($(this).attr("data-num"), 10);
    // Or
    var num = parseInt($(this).data("num"), 10);
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • In this case, I think I'll have to use .selector (class)as my selector. –  Jan 21 '13 at 09:07
  • @tasos: It doesn't matter what the selector is as long as it selects your desired elements. For instance, it could be `$("[id^=client_]")`, or something structural, or something brute force like `$("#client_1, #client_2, #client_3")`. I'd probably go with something structural or a class. :-) – T.J. Crowder Jan 21 '13 at 09:25
1

There you go:

$("#foo").click({param1: "Hello", param2: "World"}, onClick);

function onClick(event) {
    for (var param_name in event.data) {
        if (event.data.hasOwnProperty(param_name)) {
            alert('param_name = '+ event.data[param_name]);
        }
    }
}

jsFiddle

Marc Diethelm
  • 1,182
  • 1
  • 11
  • 15