Reputation: 5315
Can we put two JavaScript onclick events in one input type button tag? To call two different functions?
Upvotes: 44
Views: 218199
Reputation: 1
<button type="button" onclick="buttons()">Submit</button>
function buttons() {
alert("Part 1");
button2();
}
function button2() {
alert("Part 2");
}
Upvotes: -1
Reputation: 31173
There is no need to have two functions within one element, you need just one that calls the other two!
<a href="#" onclick="my_func()" >click</a>
function my_func() {
my_func_1();
my_func_2();
}
Upvotes: 12
Reputation: 38046
The HTML
<a href="#" id="btn">click</a>
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
Upvotes: 20
Reputation: 36839
You could try something like this as well
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>
Upvotes: 0
Reputation: 7781
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
Upvotes: 51
Reputation: 163248
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
Upvotes: 8