Question

CheckBox check state.

Asked by: judsonmusic

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

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-10-08 at 11:20:00ID22879468
Tags

checkbox

,

check

,

state

Topics

Scripting Languages

,

JavaScript

,

Miscellaneous Web Development

Participating Experts
4
Points
500
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. three state checkbox
    does anyone knows how to create a three state checkbox?
  2. CHECKBOX STATE JAVASCRIPT FUNCTION
    Hi Experts, I am trying to produce a function which checks to see whether a checkbox within a form is either checked or unchecked. The function is to be called from the checkbox itself so when the checkbox is clicked the function works out whether the checkbox has just been ...
  3. Determining the state of a checkbox
    I'm trying to determine the state of a checkbox. It's within cfform tags. Here is the basics for the checkbox: <cfinput type="Checkbox" name="frmCheckbox" checked="No"> Question 1: Does the code that determines the state of it have to b...
  4. Pseudo tri-state checkbox
    Using code similar to this: http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_21842812.html How would I go about making a tri-state checkbox using these images: http://rerendered.beapit.com/test.asp

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: stanscott2Posted on 2007-10-08 at 11:28:54ID: 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();
}

 

by: lrygielPosted on 2007-10-08 at 11:43:36ID: 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>

 

by: lrygielPosted on 2007-10-08 at 11:44:19ID: 20036023

correction
          else  {doFunctionB()}

 

by: DiscoNovaPosted on 2007-10-08 at 11:45:47ID: 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...

 

by: judsonmusicPosted on 2007-10-08 at 12:02:57ID: 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???

 

by: DiscoNovaPosted on 2007-10-08 at 12:30:52ID: 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>

 

by: LeeKowalkowskiPosted on 2007-10-09 at 01:25:18ID: 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

 

by: judsonmusicPosted on 2007-10-09 at 07:03:48ID: 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>

 

by: LeeKowalkowskiPosted on 2007-10-09 at 08:10:26ID: 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

 

by: DiscoNovaPosted on 2007-10-09 at 08:40:47ID: 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>

 

by: stanscott2Posted on 2007-10-09 at 09:11:01ID: 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

 

by: stanscott2Posted on 2007-10-09 at 09:14:45ID: 20042185

In the message above replace:

function doSomething()

with

function checkState()

Sorry

 

by: DiscoNovaPosted on 2007-10-09 at 09:21:16ID: 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:)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...