swati
swati

Reputation: 2139

How to select a button id when the button in clicked injavascript/jquery

I am new to javascript/jquery . I have a small question. I have some thing like the following in the java script file.

<button id="button1" onclick=click() />
<button id="button2" onclick=click() />
<button id="button3" onclick=click() />

so the click function looks like the follwoing

click(id){


/do some thing
}

so my question is when ever the button is clicked how can we pass the button id to the function.

<button id="button1" onclick=click("how to pass the button id value to this function") />

how can we pass the button id like "button1" to the click function when ever the button is clicked.. I would really appreciate if some one can answer to my question..

Thanks, Swati

Upvotes: 1

Views: 4296

Answers (4)

Tgr
Tgr

Reputation: 28210

That not very jQuery-ish. You should rather use event listeners:

$(function() {
    $('#button1,#button2,#button3').click(clicked);
    function clicked() {
        // "this" will refer to the clicked button inside the function
        alert($(this).attr('id'));
    }
});

Upvotes: 1

jrharshath
jrharshath

Reputation: 26583

For starters: Don't use onclick(). This is the way to do it properly.

When you get your head around all this and think "boy that's a load of cowpat to write for a litte event!", turn towards jquery.

Doing the same in jquery is simple.

Upvotes: 0

Stefan Kendall
Stefan Kendall

Reputation: 67892

You don't need to.

function handleClick(){
    //use $(this).attr("id");
    //or $(this) to refer to the object being clicked
}

$(document).ready(function(){
   $('#myButton').click(handleClick);
});

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630597

I advise the use of unobtrusive script as always, but if you have to have it inline use this, for example:

<button id="button1" onclick="click(this.id)" />

The unobtrusive way would look like this:

$("button").click(function() {
  click(this.id);
});

Upvotes: 2

Related Questions