0

I have read many topics how to handle Javascript's onclick vs Jquery;s .click(), but I can't figure out how to pass parameters using jQuery.

1st option - Javascript, HTML

The HTML

<input type="button" onclick="doAction(<?=$id?>,'order');" />

Therefore in JS I can do

function doAction(id,type){

 //do something here

}

2nd option - jQuery,HTML

The HTML

<input type="button" id="trigger" />

So jQuery becomes

$("#trigger").click(function() {

   //do something here

 });

Do I have to do something like (in this case how do I know the values of id and type?)

  $("#trigger").click({id: "???", type: "????"}, other_function);

  function other_function(event){
     id = event.data.param1;
     type = event.data.param2;
   }

Do I have to "pass parameters" by using

  HTML
  <input type="hidden" id="id" value="<?=$id?>" />
  <input type="hidden" id="type" value="order" />

  jQuery

   $("#trigger").click(function(){
      var id = $("#id").val();
      var type = $("#type").val();
      //do something

   });

I want to avoid using onclick() as I have read that it should be avoided. I just need a suitable way to pass parameters as I did by using onclick().

1
  • Sure, there some ways to do it. I just want to write nice and clean code. So, I'm wondering if there is another way Commented Jan 18, 2013 at 15:41

4 Answers 4

6

You can use data to pass the data() to event.

Live Demo

 <input type="hidden" id="id" data-idatt="123" />
 <input type="hidden" id="type" value="order" />

 $("#trigger").click(function(){
    var id = $("#id").data("idatt").val();
 });
Sign up to request clarification or add additional context in comments.

2 Comments

As a side note, "idAtt" will have to be lowercase here, so data("idatt"). To get "idAtt" your data tag would be data-id-att.
so the hyphen-to-camelcase applies on data attributes too, I thought it only applied to CSS properties. Well, in this case it is more camelcase-to-hyphen. Learning something new everyday - here's the fiddle to see it in practice.
0

You don't need to take parameter from outside and don't need hidden field either

$("#trigger").click(function(){
      var id = <?=$id?>;
      //do something
   });

Comments

0

using chrome open up the console and try this

$(#trigger);
$(#trigger).click(function(e) {
  console.log(
               $(this),
               $(this).attr('type') 
             );
});

the function has a hidden variable called this and is the element you triggered the event.

Comments

0
$("#myElement").click({ "a": 1, "b": 2 }, function (e) {
    alert(e.data.a); // alerts 1
    alert(e.data.b); // alerts 2
});

1 Comment

Even though this is a good solution, OP already wrote it in the question, and usually JS is in a separate file from the generated HTML which OP is populating with PHP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.