How to send multiple parameters to jQuery click function?

16,385

Solution 1

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.

Solution 2

The correct way is:

<a href="#" id="myanchor" data-nm="state_name" data-id="state_id">ADD STATE </a>

<script type="text/javascript">
$(document).ready(function(event) {
   event.preventDefault();
   $('#myanchor').on('click', function() {
      openbox_state( $(this).data('nm') , $(this).data('id'));
   });
});
</script>

Solution 3

Your Jquery Code:

<script language="javascript" type="text/javascript">
 var state_name=$('#txtName').val();
 var state_id=$('#txtid').val();
$(document).ready(function () {
     $('a').click(function(){
        showState(state_name,state_id);
         });
});



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

</script>  

Your HTML:

<a href="javaScript:void(0);">ADD STATE </a>
<input type="text" id="txtName" value="Tom Cruse" />
<input type="text" id="txtid" value="1" />

this jquery take the values from inputs, by using their id and use them as parameters to call the method.

Share:
16,385
edaklij
Author by

edaklij

Looking Up.

Updated on June 05, 2022

Comments

  • edaklij
    edaklij almost 2 years

    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);
    }