9

Is it possible to add a onclick event to any button by jquery or something like we add class?

function onload()
{

//add a something() function to button by id

}

4 Answers 4

14

Calling your function something binding the click event on the element with a ID

$('#id').click(function(e) {
    something();
});

$('#id').click(something);

$('#id').bind("click", function(e) { something(); });

Live has a slightly difference, it will bind the event for any elements added, but since you are using the ID it probably wont happen, unless you remove the element from the DOM and add back later on (with the same ID).

$('#id').live("click", function(e) { something(); });

Not sure if this one works in any case, it adds the attribute onclick on your element: (I never use it)

$('#id').attr("onclick", "something()");

Documentation

Sign up to request clarification or add additional context in comments.

2 Comments

some comment would've been neat for these lines. He may not get what they are good for.
I needed to set the click function when a checkbox was checked. The only method that worked for me was bind. Thanks!
7

Yes. You could write it like this:

$(document).ready(function() {
  $(".button").click(function(){
    // do something when clicked
  });
});

Comments

2
$('#id').click(function() {
    // do stuff
});

Comments

2

Yes. Something like the following should work.

$('#button_id').click(function() {
  // do stuff
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.