Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i run a function when multiple buttons are clicked

Im trying to make it when buttons are clicked it causes a function which returns it to true and when it returns to true another button checks that and causes another function to run.

WHAT I TRIED:

    function done1(){
        return true;
    }
    function done2(){
        return true;
    }
var done1=done1();
var done2=done2();
function done3(){
    if ( done1 && done2){
        alert('hello');
    }
}
<button id="1" onclick="done1(); ">1</button>
<button id="2" onclick="done2()">2</button>
<button id="3" onclick="done3()">3</button>

When i press the 3rd button it still shows the alert even when the buttons are not clicked. Its supposed to make it return true when the buttons are clicked but it does it even if its not clicked.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you need is instead of returning a value from each function, change value of a variable. For example, something like this:

const trigger = [0, 0];

function done1()
{
  trigger[0] = 1;
}
function done2()
{
  trigger[1] = 1;
}
function done3(){
    if ( trigger[0] + trigger[1] == 2){
        alert('hello');
    }
}
<button id="1" onclick="done1()">1</button>
<button id="2" onclick="done2()">2</button>
<button id="3" onclick="done3()">3</button>

Or if you want be able toggle button’s state (aka second press will undo) you could store values of each button as bits (up to 32 buttons) with something like this:

let trigger = 0;

function done(val)
{
  if (!val && trigger == 7)
        alert('hello');
  else  
    trigger = trigger ^ val; //binary XOR
}
<button id="1" onclick="done(1)">1</button>
<button id="2" onclick="done(2)">2</button>
<button id="3" onclick="done(4)">3</button>
<button id="4" onclick="done()">4</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading