How to send multiple parameters to jQuery click function?

edaklij picture edaklij · Nov 30, 2012 · Viewed 15.7k times · Source

Possible Duplicate:
How to send multiple arguments to jQuery click function?

I want to pass multiple arguments to a Jquery function. Below is the Javascript sample code. I want to convert this javascript function to a jquery function. How can I pass that arguments into a jquery onclick event?

<a onclick="showState('state_name','state_id')">ADD STATE </a>

function showState(state_name,state_id){
openbox_state(state_name,state_id);
}

Answer

raina77ow picture raina77ow · Nov 30, 2012

Perhaps I'd use datasets here:

HTML:

<a data-state_name="state_name" data-state_id="state_id" >ADD STATE</a>

JS:

$(function() {
...
  $('a[data-state_id]').click(function() {
    var $this = $(this);
    showState($this.data('state_name'), $this.data('state_id'));
    return false;
  });
...
});

You actually don't have to jwrap the clicked object, as you can get the attribute values with either dataset API (if you have the luxury of not supporting IE9-, though) or simple getAttribute method. Yet I found this syntax more clean and readable.