Acubi
Acubi

Reputation: 2783

How to pass parameter to click event in Jquery

I want to change the following JS to Jquery. But I don't know how to pass parameter to click event in Jquery. Can anyone help me, thanks!

<script type="text/javascript">

function display(id){

    alert("The ID is "+id);
    }
</script>

<input id="btn" type="button" value="click" onclick="display(this.id)" />

Upvotes: 17

Views: 123566

Answers (4)

Eugen Konkov
Eugen Konkov

Reputation: 25133

As DOC says, you can pass data to the handler as next:

// say your selector and click handler looks something like this...
$("some selector").on('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);

    // access element's id where click occur
    alert( event.target.id ); 
}

Upvotes: 15

Ortiga
Ortiga

Reputation: 8814

You don't need to pass the parameter, you can get it using .attr() method

$(function(){
    $('elements-to-match').click(function(){
        alert("The id is "+ $(this).attr("id") );
    });
});

Upvotes: 11

jmar777
jmar777

Reputation: 39649

Better Approach:

<script type="text/javascript">
    $('#btn').click(function() {
      var id = $(this).attr('id');
      alert(id);
    });
</script>

<input id="btn" type="button" value="click" />

But, if you REALLY need to do the click handler inline, this will work:

<script type="text/javascript">
    function display(el) {
        var id = $(el).attr('id');
        alert(id);
    }
</script>

<input id="btn" type="button" value="click" OnClick="display(this);" />

Upvotes: 26

Pantelis
Pantelis

Reputation: 6136

 $('elements-to-match').click(function(){
        alert("The id is "+ this.id );
    });

no need to wrap it in a jquery object

Upvotes: 4

Related Questions