[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

CheckBox check state.

Posted on 2007-10-08
13
Medium Priority
?
601 Views
Last Modified: 2010-04-16
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
0
Comment
Question by:judsonmusic
  • 4
  • 3
  • 2
  • +2
13 Comments
 
LVL 15

Expert Comment

by:stanscott2
ID: 20035915
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();
}
0
 
LVL 4

Expert Comment

by:lrygiel
ID: 20036018
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>
0
 
LVL 4

Expert Comment

by:lrygiel
ID: 20036023
correction
          else  {doFunctionB()}
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 7

Expert Comment

by:DiscoNova
ID: 20036037
<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...
0
 
LVL 3

Author Comment

by:judsonmusic
ID: 20036153
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???
0
 
LVL 7

Expert Comment

by:DiscoNova
ID: 20036368
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>
0
 
LVL 16

Expert Comment

by:LeeKowalkowski
ID: 20039268
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
0
 
LVL 3

Author Comment

by:judsonmusic
ID: 20041022
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>
0
 
LVL 16

Expert Comment

by:LeeKowalkowski
ID: 20041606
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
0
 
LVL 7

Expert Comment

by:DiscoNova
ID: 20041885
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>
0
 
LVL 15

Expert Comment

by:stanscott2
ID: 20042153
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

0
 
LVL 15

Expert Comment

by:stanscott2
ID: 20042185
In the message above replace:

function doSomething()

with

function checkState()

Sorry
0
 
LVL 7

Accepted Solution

by:
DiscoNova earned 1500 total points
ID: 20042241
@stanscott2: Perhaps you need to further modify the version of yours, because currently it contains hardcoded elements, and only is able handle the three checkboxes that are shown (and the one "div" possibly, that is not shown). However, the author has told us that s/he has multiple "sets" of these checkboxes, which modify a state of some other element (and I understood that the said element is also different for each of the given sets).

That is the reason why my code is much harder to call - it is a lot more versatile than the other suggestions given so far (at least on my opinion, but then again, I might not be entirely impartial judge on the matter:)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When it comes to write a Context Sensitive Help (an online help that is obtained from a specific point in state of software to provide help with that state) ,  first we need to make the file that contains all topics, which are given exclusive IDs. …
The first step to building an amazing About page is to figure out what you want the page to say about your company. You then must grab the attention of the reader, boast a bit, tell a story and let others brag about you. With a little bit of thought…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Suggested Courses
Course of the Month18 days, 20 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question