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

}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
esafwan
  • 17,311
  • 33
  • 107
  • 166

4 Answers4

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

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • some comment would've been neat for these lines. He may not get what they are good for. – gblazex Jul 10 '10 at 16:51
  • I needed to set the click function when a checkbox was checked. The only method that worked for me was bind. Thanks! – Trent Jun 20 '13 at 07:56
7

Yes. You could write it like this:

$(document).ready(function() {
  $(".button").click(function(){
    // do something when clicked
  });
});
Ken Earley
  • 769
  • 4
  • 14
2
$('#id').click(function() {
    // do stuff
});
melhosseiny
  • 9,992
  • 6
  • 31
  • 48
2

Yes. Something like the following should work.

$('#button_id').click(function() {
  // do stuff
});
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174