Reputation: 55760
How do you change the JavaScript that will execute when a form button is clicked?
I've tried changing its onClicked and its onclicked child attributes like so:
$('mybutton').onClick = 'doSomething';
and
$('mybutton').attributes["onclick"] = 'doSomething()';
Neither seem to work. My other options are:
Neither seem very elegant.
I'm using Prototype as a js library so it that has any useful tools I can use them.
Upvotes: 2
Views: 9500
Reputation: 31
If the original onclick event was set through HTML attributes, you can use the following to overwrite it:
$("#myButtonId").setAttribute("onclick", "myFunction();");
Upvotes: 3
Reputation: 3170
I found a solution for your issue with prototype under firefox:
$("#myButtonId").writeAttribute('onclick', ''); // first remove the attribute
$("#myButtonId").observe('click', function () { ... }); // then add the event
Upvotes: 0
Reputation: 115332
Using the Prototype framework you can do:
Event.observe("mybutton", "click", clickHandler);
or:
Event.observe("mybutton", "click", function() {
alert("Button clicked!");
});
or:
$("mybutton").observe("click", clickHandler);
or:
$("mybutton").observe("click", function() {
alert("Button clicked!");
});
Upvotes: 2
Reputation: 10420
Last I used Prototype, it was something like this:
Event.observe('mybutton', 'click', doSomething);
By the way, your examples might've even worked if you didn't quote the function names.
EDIT: Yes, Element.observe(element, eventName, handler) and someElement.observe(eventName, handler) also work. And don't quote the handler name - you want to pass the function not a string!
Upvotes: 0
Reputation: 227
In JQuery it's
$("#myButtonId").click(myFunction);
function myFunction(){
alert("Clicked");
}
Or if you want to put the function inline:
$("#myButtonId").click(function(){
alert("Clicked");
});
If you are using JQuery firstly make sure you use the relevant selector prefix (IE: If your using the Id of the element put a # in front of it). Secondly it's the click method to assign a callback to the click event.
Upvotes: 0
Reputation: 27581
The general way to set an onclick handler in javascript is to set onclick
to a function, by passing it the name of a function directly, not in a string. So if myButton
is set to a DOM Element, you would write:
myButton.onclick = doSomething;
So when you click the 'mybutton' button, the doSomething
function will be called as doSomething()
. For anonymous functions, you can write:
myButton.onclick = function() {
alert("myButton was clicked!");
};
Upvotes: 1
Reputation: 5693
For Prototype, I believe that it would be something like this:
$("mybutton").observe('click', function() {
// do something here
});
EDIT: Or, as it says in the documentation, you could simply specify the function you want to call on click:
$('mybutton').observe('click', respondToClick);
function respondToClick(event) {
// do something here
}
But this is all, again, Prototype-specific.
Upvotes: 2