Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call two methods on button's onclick method in HTML or JavaScript?

How to call two methods on button's onclick method in HTML or JavaScript ?

like image 868
Nirav Jain Avatar asked May 04 '11 10:05

Nirav Jain


People also ask

Can I call two function in onClick JavaScript?

Greetings! Yes, you can call two JS Function on one onClick.

Can you have two onClick events HTML?

So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.

How do you call two methods on onClick React?

To call multiple functions onClick in React:Set the onClick prop on the element. Call the other functions in the event handler function. The event handler function can call as many other functions as necessary.

Can we pass two functions onClick event React?

The first solution to perform multiple onClick events in React is to include all of your actions inside of a function and then call that single function from the onClick event handler. Let's explore how to do that in a React Component: import React from 'react'; function App() { function greeting() { console.


2 Answers

  1. Try this:

    <input type="button" onclick="function1();function2();" value="Call2Functions" /> 
  2. Or, call second function at the end of first function:

       function func1(){      //--- some logic      func2();    }     function func2(){     //--- some logic    } 

    ...and call func1() onclick of button:

    <input type="button" onclick="func1();" value="Call2Functions" /> 
like image 64
Harry Joy Avatar answered Sep 22 '22 17:09

Harry Joy


As stated by Harry Joy, you can do it on the onclick attr like so:

<input type="button" onclick="func1();func2();" value="Call2Functions" /> 

Or, in your JS like so:

document.getElementById( 'Call2Functions' ).onclick = function() {     func1();     func2(); }; 

Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):

var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),     func1 = Call2FunctionsEle.onclick;  Call2FunctionsEle.onclick = function() {     if( typeof func1 === 'function' )     {         func1();     }     func2(); }; 

If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:

document.getElementById( 'Call2Functions' ).onclick = function() {     func1.apply( this, arguments );     func2.apply( this, arguments ); }; 
like image 34
JAAulde Avatar answered Sep 21 '22 17:09

JAAulde