faqts : Computers : Programming : Languages : JavaScript : Forms : Buttons

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

16 of 20 people (80%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How do I validate that a button has been clicked. Onclick of button A, was button B ever clicked?

Nov 29th, 2001 17:06
Jean-Bernard Valentaten, Danny Sementilli,


Well, you could use flags for example. When button A gets clicked, you
set a flag and so on.
Something like this:
<script language="JavaScript">
<!--
  var flagA = false;
  var flagB = false;
  function validateBtns()
  {
    if (flagA && flagB)
      doSomething();
    else
      alert("You haven't clicked all the Buttons");
  }
//-->
</script>
and then in the onclick-handler of your buttons:
<input type="button" name="buttonA" onClick="flagA = true;
validateBtns();" value="Button A">
<input type="button" name="buttonB" onClick="flagB = true;
validateBtns();" value="Button B">
I use those kinda tricks alot even in software development.
Of course if you use a lot of buttons this get's a little messy setting
the flags, so I use arrays then.
Like this:
<script language="JavaScript">
<!--
  var flags = new Array();
  var maxBtns = 9; //the exact number of buttons you have
  //this initializes the flags with 'false'
  for (i = 0; i < maxBtns; i++)
    flags[i] = false;
  //this function will set any button-flag to true
  function setButtonFlag(btnNumber)
  {
    flags[btnNumber] = true;
  }
  //this will validate the buttons
  function validateBtns()
  {
    var flagSum = false;
    for (i = 0; i < maxBtns; i++)
    {
      //by using a logical 'and' you make sure that you only
      //get true if all flags are true (true && false = false)
      flagSum = flagSum && flags[i];
    }
    return flagSum;
  }
  //this will decide what to do based on the validation
  function doWhat()
  {
    if (validateBtns())
      alert("All Buttons clicked!"); //or whatever you want to happen
    else
      alert("Not all Buttons clicked!"); //or whatever should happen
  }
//-->
</script>
and now in your onClick-handlers:
<input type="button" name="button0" onClick="setButtonFlag(0);
doWhat();" value="Button 1">
<input type="button" name="button1" onClick="setButtonFlag(1);
doWhat();" value="Button 2">
always keep in mind, that arrays start with element 0, not element 1
(this is JavaScript, not Pascal or Basic *g*).
All of this can be programmed, so that it all gets even more dynamic,
but I'm sure you'll figure out how :)
HTH,
Jean