Link to home
Start Free TrialLog in
Avatar of judsonmusic
judsonmusicFlag for United States of America

asked on

CheckBox check state.

Can someone tell me a simple way to check the state of a checkbox in javascript and if checked do a function, if not checked, do another function???

I have 4 checkboxed and is long as one is checked want to do function a otherwise do fuction b

Thanks,

Judson
Avatar of stanscott2
stanscott2

Let's say that these are the only checkboxes on the page.  then, you do this:

function doSomething() {
     var inp = document.getElementsByTagName("input");
     for (var t=0; t<inp.length; t++) {
          if (inp[t].type=="checkbox" && inp[t].checked) {
               doFunctionA();
               return;              // exit function
          }
     }
     doFunctionB();
}
If you want to keep it simple, and know the ID's of the 4 check boxes, try:

<script language=javascript>
function isChecked(){
    if (document.getElementById("checkbox1").checked ||
        document.getElementById("checkbox2").checked ||
        document.getElementById("checkbox3").checked ||
        document.getElementById("checkbox4").checked ) {doFunctionA()}
    else  {doFunctionA()}
}
</script>

<form>
    <input type="checkbox" id="checkbox1" value="Y" />
    <input type="checkbox" id="checkbox2" value="Y" />
    <input type="checkbox" id="checkbox3" value="Y" />
    <input type="checkbox" id="checkbox4" value="Y" />
    <input type="submit" value="click" onclick="isChecked()" />
</form>
correction
          else  {doFunctionB()}
<html>
  <head>
    <title>Test</title>
    <script type="text/javascript"><!--
      function a() {  alert("Foo");  }
      function b() {  alert("Bar");  }

      function foobar() {
        var cbs = ["cb1","cb2","cb3","cb4"];
        var anyChecked = false;
        for (var i in cbs) {
          anyChecked = anyChecked || !!(document.getElementById(cbs[i]).checked);
        }
        if (anyChecked) {
          a();
        } else {
          b();
        }
      }
    // --></script>
  </head>
  <body>
    <form>
      <input type="checkbox" name="cb1" id="cb1">
      <input type="checkbox" name="cb2" id="cb2">
      <input type="checkbox" name="cb3" id="cb3">
      <input type="checkbox" name="cb4" id="cb4">
    </form>
    <a href="#" onclick="foobar(); return false;">Do action based on checkboxes' states</a>
  </body>
</body>

Of course, if you wish, you could execute "foobar();" on the input-element's onclick/onchange, or any other way...
Avatar of judsonmusic

ASKER

let me be more specific in what I need as there may be a simpler way.

I have a list or 12predictors each with 4-10 sub predictors that have checkboxes on each of them.

lets say in the 1st predictor, there are 5 subpreds. A person checks one of them.

My script will show strategies at the bottom of the page that apply to any of the 5 subpreds. so as long as one of them is checked, the class of the strategy is 'visible'

If none of themn are checked it is nonvisisble.

I can get the strategy to become visible on the onclick, but how do I change it back if someone deselects all of the boxes???
The onclick is fired also when deselecting the box. You just need to point the onclick to the appropriate function like this (for example, modify as required) ...

<html>
  <head>
    <title>Test</title>
    <script type="text/javascript"><!--
      function foobar(cbs, onAnyChecked, onNoneChecked) {
        var anyChecked = false;
        for (var i in cbs) {
          anyChecked = anyChecked || !!(document.getElementById(cbs[i]).checked);
        }
        if (anyChecked) {
          onAnyChecked();
        } else {
          onNoneChecked();
        }
      }
      function showSubs(x) {
        document.getElementById(x).style.display="block";
      }
      function hideSubs(x) {
        document.getElementById(x).style.display="none";
      }
    // --></script>
  </head>
  <body>
    <form>
      <h1>1</h1>
      <input type="checkbox" name="cb1.1" id="cb1.1" onclick="foobar(['cb1.1','cb1.2','cb1.3','cb1.4'], function(){ showSubs('x1'); }, function(){ hideSubs('x1'); });">
      <input type="checkbox" name="cb1.2" id="cb1.2" onclick="foobar(['cb1.1','cb1.2','cb1.3','cb1.4'], function(){ showSubs('x1'); }, function(){ hideSubs('x1'); });">
      <input type="checkbox" name="cb1.3" id="cb1.3" onclick="foobar(['cb1.1','cb1.2','cb1.3','cb1.4'], function(){ showSubs('x1'); }, function(){ hideSubs('x1'); });">
      <input type="checkbox" name="cb1.4" id="cb1.4" onclick="foobar(['cb1.1','cb1.2','cb1.3','cb1.4'], function(){ showSubs('x1'); }, function(){ hideSubs('x1'); });">
      <h1>2</h1>
      <input type="checkbox" name="cb2.1" id="cb2.1" onclick="foobar(['cb2.1','cb2.2','cb2.3','cb2.4'], function(){ showSubs('x2'); }, function(){ hideSubs('x2'); });">
      <input type="checkbox" name="cb2.2" id="cb2.2" onclick="foobar(['cb2.1','cb2.2','cb2.3','cb2.4'], function(){ showSubs('x2'); }, function(){ hideSubs('x2'); });">
      <input type="checkbox" name="cb2.3" id="cb2.3" onclick="foobar(['cb2.1','cb2.2','cb2.3','cb2.4'], function(){ showSubs('x2'); }, function(){ hideSubs('x2'); });">
      <input type="checkbox" name="cb2.4" id="cb2.4" onclick="foobar(['cb2.1','cb2.2','cb2.3','cb2.4'], function(){ showSubs('x2'); }, function(){ hideSubs('x2'); });">
      <h1>3</h1>
      <input type="checkbox" name="cb3.1" id="cb3.1" onclick="foobar(['cb3.1','cb3.2','cb3.3','cb3.4'], function(){ showSubs('x3'); }, function(){ hideSubs('x3'); });">
      <input type="checkbox" name="cb3.2" id="cb3.2" onclick="foobar(['cb3.1','cb3.2','cb3.3','cb3.4'], function(){ showSubs('x3'); }, function(){ hideSubs('x3'); });">
      <input type="checkbox" name="cb3.3" id="cb3.3" onclick="foobar(['cb3.1','cb3.2','cb3.3','cb3.4'], function(){ showSubs('x3'); }, function(){ hideSubs('x3'); });">
      <input type="checkbox" name="cb3.4" id="cb3.4" onclick="foobar(['cb3.1','cb3.2','cb3.3','cb3.4'], function(){ showSubs('x3'); }, function(){ hideSubs('x3'); });">
      <h1>4</h1>
      <input type="checkbox" name="cb4.1" id="cb4.1" onclick="foobar(['cb4.1','cb4.2','cb4.3','cb4.4'], function(){ showSubs('x4'); }, function(){ hideSubs('x4'); });">
      <input type="checkbox" name="cb4.2" id="cb4.2" onclick="foobar(['cb4.1','cb4.2','cb4.3','cb4.4'], function(){ showSubs('x4'); }, function(){ hideSubs('x4'); });">
      <input type="checkbox" name="cb4.3" id="cb4.3" onclick="foobar(['cb4.1','cb4.2','cb4.3','cb4.4'], function(){ showSubs('x4'); }, function(){ hideSubs('x4'); });">
      <input type="checkbox" name="cb4.4" id="cb4.4" onclick="foobar(['cb4.1','cb4.2','cb4.3','cb4.4'], function(){ showSubs('x4'); }, function(){ hideSubs('x4'); });">
    </form>
    <hr>
    <div id="x1" style="display:none">X1</div>
    <div id="x2" style="display:none">X2</div>
    <div id="x3" style="display:none">X3</div>
    <div id="x4" style="display:none">X4</div>
  </body>
</body>
I'm not sure you need to iterate through all the checkboxes to see if any are checked, just keep a count of the number of checked checkboxes, and increment it when checked and decrement it when unchecked.

--
Lee
Why wont this work???

this for the function:
////////////////////////////////////////////////////////////////////////////////////////////////////
<script>
function checkState(cbs,x)
            {
        var anyChecked = false;
        for (var i in cbs) {
          anyChecked = anyChecked || !!(document.getElementById(cbs[i]).checked);
        }
        if (anyChecked)
            {
        document.getElementById(x).style.display="block";
        }
            else
            {
            document.getElementById(x).style.display="none";
            }
      }
</script>


this for the code

<div class="novis" id="p1">
        <ul>
          <li><input name="P1" type="checkbox" id="PP1" onclick="checkState(this.id,s1);"> particularly depression</li>
            <li><input name="P1" type="checkbox" id="PP1" onclick="checkState(this.id,s1);"/> others may include bipolar or schizophrenia</li>
            <li><input name="P1" type="checkbox" id="PP1" onclick="checkState(this.id,s1);"/> this group often has difficulty following a medication regimen</li>
        </ul>
    </div>
Cannot have multiple elements with the same ID.

Cannot pass ID into checkState (which becomes 'cbs'), then do for(var i in cbs).

Cannot pass s1 into checkState (which becomes 'x') unless s1 is a global javascript variable.

--
Lee
I'm singing the chorus verse...

Because checkState is designed to check _multiple_checkboxes_ (not just one) at the same time, it expects to have an array (of strings that correspond to id-values to check) as it's first variable, this.id is not an array.

The second argument for checkState should be a string corresponding to the id-value that should be shown or hidden. At this point, you're passing argument s1, which is possibly something other (it is impossible to tell based on the snippet you've included).

And as LeeKowalski said, you should not have multiple elements with the same id. The id-argument of an element is supposed to be an unique _id_entifier within the document.

I believe the code you're attempting to get to work is more or less something not entirely different from:

<div class="novis" id="p1">
      <ul>
            <li><input type="checkbox" id="PP1.1" onclick="checkState(['PP1.1','PP1.2','PP1.3'],'s1');"> particularly depression</li>
            <li><input type="checkbox" id="PP1.2" onclick="checkState(['PP1.1','PP1.2','PP1.3'],'s1');"> others may include bipolar or schizophrenia</li>
            <li><input type="checkbox" id="PP1.3" onclick="checkState(['PP1.1','PP1.2','PP1.3'],'s1');"> this group often has difficulty following a medication regimen</li>
      </ul>
</div>
You can make this MUCH simpler.  I'm adding an onclick event to the DIV:

<div class="novis" id="p1" onclick="checkState()">
        <ul>
          <li><input name="P1" type="checkbox" id="PP3"  /> particularly depression</li>
            <li><input name="P1" type="checkbox" id="PP2" /> others may include bipolar or schizophrenia</li>
            <li><input name="P1" type="checkbox" id="PP3" /> this group often has difficulty following a medication regimen</li>
        </ul>
    </div>

And modify my original post slightly:

function doSomething() {
     var inp = document.getElementById("p1").getElementsByTagName("input");
     for (var t=0; t<inp.length; t++) {
          if (inp[t].type=="checkbox" && inp[t].checked) {
               document.getElementById("s1").style.display="block";
               return;              // exit function
          }
     }
     document.getElementById("s1").style.display="none";
}

Your function doesn't work, by the way, because you need to pass the id of the element as a string:

"s1"  NOT s1

In the message above replace:

function doSomething()

with

function checkState()

Sorry
ASKER CERTIFIED SOLUTION
Avatar of DiscoNova
DiscoNova
Flag of Finland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial