Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a function to onclick event by Javascript!

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

}
like image 529
esafwan Avatar asked Jul 10 '10 16:07

esafwan


People also ask

How do you write a function on onclick event?

Just invoke the code you're trying to invoke: onclick="alert('hello')" If you want to define a function, do that separately in your JavaScript code and just invoke the function in onclick . (Or, even better, attach it as a handler from the JavaScript code so you're not writing in-line JavaScript in your HTML.)

Can we add two functions onclick event in JavaScript?

Greetings! Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.

How onclick function works in JavaScript?

The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.

Can we use onclick in JavaScript?

The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.


2 Answers

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

  • Click
  • Bind
  • Live
  • Attr
like image 115
BrunoLM Avatar answered Oct 26 '22 19:10

BrunoLM


Yes. You could write it like this:

$(document).ready(function() {
  $(".button").click(function(){
    // do something when clicked
  });
});
like image 42
Ken Earley Avatar answered Oct 26 '22 19:10

Ken Earley