3

I got on how to check/unchecked or hide/show when one checkbox is checked but what im looking for is when I have 5 checkboxes Fastfood, Catering, Carryout, Delivery and Bar when user clicked Fastfood ,rest checkboxes are disable, when user checked Catering, rest are disable but when user checked Carryout only Fastfood and Catering are disable. Then when user unchecked, all checkboxes back to enable/show. thanks! –

Here my code:

<script type="text/javascript">
function HideOrShowStuff(controlToHide1)
{


       if (document.getElementById)
   {
          if(controlToHide1==1)
      {
      document.getElementById('2').disabled=true;
        document.getElementById('3').disabled = true;
          document.getElementById('4').disabled = true;
           document.getElementById('5').disabled = true;
           document.getElementById('1').disabled = false;
             }
        if(controlToHide1==2)
      { 
         document.getElementById('1').disabled=true;
        document.getElementById('2').disabled = false;
          document.getElementById('4').disabled = true;
           document.getElementById('5').disabled = true;
           document.getElementById('3').disabled = true;
              }
                  if(controlToHide1==3)
      { 
          document.getElementById('1').disabled=true;
        document.getElementById('2').disabled = true;
          document.getElementById('4').disabled = false;
           document.getElementById('5').disabled = false;
           document.getElementById('3').disabled = false;
              }
                  }
        }

</script>

 Type of restaurant are you?<br /> <br /> 
<input type="checkbox" name="restaupop1"  id="1"value="fastfood" onclick="HideOrShowStuff(1)"    <?PHP print $fastfood_status; ?>> Fast Food/Drive Thru  <br />
<input type="checkbox" name="restaupop2" id="2"value="catering"  onclick="HideOrShowStuff(2); setVisible('restaubar');"   <?PHP print $catering_status; ?>> Catering<br />
<input type="checkbox"  name="restaupop3" id="3" value="carryout"  onclick="HideOrShowStuff(3)"   <?PHP print $carryout_status; ?>> Carry-Out<br />
<input type="checkbox" name="restaupop4" id="4"value="delivery"   onclick="setVisible('barpop1');"  <?PHP print $delivery_status; ?>> Delivery<br />
<input type="checkbox" name="restaupop5" id="5"value="bargrill" onclick="setVisible('restaubar');"     <?PHP print $bargrill_status; ?>>Bar/Grill
dinah
  • 45
  • 1
  • 1
  • 5
  • You have PHP code in there too, what is the HTML version of this? I can't tell until the document is rendered. – Incognito May 19 '11 at 15:08
  • the html version is very long... but to make it sure..this is what im looking for.....i got on how to check/unchecked or hide/show when one checkbox is checked but let see when I have 5 checkboxes Fastfood, Catering, Carryout, Delivery and Bar when user clicked Fastfood ,rest checkboxes are disable, when user checked Catering, rest are disable but when user checked Carryout only Fastfood and Catering are disable. Then when user unchecked, all checkboxes back to enable/show. thanks! – – dinah May 19 '11 at 19:07

6 Answers6

3

All in all, not too difficult.

http://jsfiddle.net/A5TGf/19/

HTML:

<form action="./" id="checkForm" method="post">
    <fieldset>
        <label for="foo">foo</label>
        <input type="checkbox" id="foo" value="foo" />
        <label for="bar">bar</label>
        <input type="checkbox" id="bar" value="bar" />
        <label for="baz">baz</label>
        <input type="checkbox" id="baz" value="baz" />
    </fieldset>
</form>

JS:

var form = document.getElementById("checkForm");
form.onclick = delegateFormClick;

addChangeHandlers(form);

function addChangeHandlers(form)
{
   for(var i=0;i<form.elements.length;i++)
   {
       var element = form.elements[i];
       if(element.tagName === "INPUT" && element.type === "checkbox")
       {
           if(!element.onchange)
           {
               element.onchange = checkBoxChanged;   
           }
       }
   }  
}

function delegateFormClick(evt)
{
    var target;
    if(!evt)
    {
        //Microsoft DOM
        target = window.event.srcElement;
    }else if(evt)
    {
        //w3c DOM
        target = evt.target;
    }
    if(target.nodeType === 1 && target.tagName === "INPUT" && target.type === "checkbox")
    {
        if(target.checked)
        {
            disableCheckBoxes(target.id, document.getElementById("checkForm"));
        }else if(!target.checked)
        {
            enableCheckBoxes(document.getElementById("checkForm"));
        }  
    }
}

function checkBoxChanged()
{
    if(this.checked)
    {
       disableCheckBoxes(this.id, document.getElementById("checkForm"));
    }else if(!this.checked)
    {
        enableCheckBoxes(document.getElementById("checkForm"));  
    }
}

function disableCheckBoxes(id, form)
{
    var blacklist = [];
    if(id)
    {
        switch(id)
        {
            case "foo":
            blacklist = ["bar", "baz"];
            break;
            case "bar":
            blacklist = ["foo"];
            break;
            case "baz":
            blacklist = ["foo", "bar"];
            break;
        }   
    }else
    {
        throw new Error("id is needed to hard-wire input blacklist");   
    }
    for(var i=0;i<blacklist.length;i++)
    {
        var element = document.getElementById(blacklist[i]);
        if(element && element.nodeType === 1)
        {
            //check for element
            if(element.tagName === "INPUT" && element.type === "checkbox" && !element.checked)
            {
                element.disabled = "disabled";
            }
        }else if(!element || element.nodeType !== 1)
        {
            throw new Error("input blacklist item does not exist or is not an element");
        }
    }   
}

function enableCheckBoxes(form)
{
    for(var i=0;i<form.elements.length;i++)
    {
        var element = form.elements[i];
        if(element.tagName === "INPUT" && element.type === "checkbox" && !element.checked)
        {
            element.disabled = "";
        }
    }   
}

Some quick notes on what I'm doing:

  1. I'm using event delegation to minimize the amount of event handlers. The form listens for a click event bubbling up, then calls a function depending on which element was clicked and its checked DOM property.
  2. I'm traversing the HTMLFormElement.elements collection to easily access the checkboxes.
  3. I'm setting the disabled DOM property to "disabled" on the checkbox if it's not the target checkbox.
  4. I'm setting the disabled DOM property to "" (an empty string) on the checkbox if no checkboxes are checked.
  5. This also works if the user selects the checkbox by tabbing/entering or another method via the onchange handler.
  6. This code should work in IE, though I'm having some serious problems with IE via Wine at work, so I'll have to test later.
  7. It uses a "blacklist", which is an array that contains ids to checkboxes you don't want enabled when the corresponding checkbox is clicked.

Let me know if you're looking for anything further.

  • you're close Matt, but i would like when user click foo, bar and baz are disable/hide, then when user click bar - only foo is disable. Thanks! – dinah May 19 '11 at 18:49
  • Is there a set method to that? In other words, is one specific input to be disabled when another is clicked? What's the pattern? –  May 19 '11 at 18:52
  • yes is a set of method, we used this scenario to figure what is the right product base on type of restaurant they are. – dinah May 19 '11 at 19:01
  • what im looking for is when I have 5 checkboxes Fastfood, Catering, Carryout, Delivery and Bar when user clicked Fastfood ,rest checkboxes are disable, when user checked Catering, rest are disable but when user checked Carryout only Fastfood and Catering are disable. Then when user unchecked, all checkboxes back to enable/show. thanks! – – dinah May 19 '11 at 19:01
  • 1
    I've made a "blacklist" feature that enables you to hard-wire a list of checkbox ids that you want disabled: http://jsfiddle.net/A5TGf/9/. Let me know if that's what you're looking for. –  May 19 '11 at 19:12
  • Thanks, Matt your a big help! :D – dinah May 19 '11 at 19:36
  • Don't forget to mark the question as "accepted" if you're satisfied (look for the checkmark on the left). –  May 19 '11 at 19:39
  • I made a faux pas with one line of the solution. Please note the revised code above. The pertinent line *was*: `}else if(!element || element.nodeType !== 3)`, but is now: `}else if(!element || element.nodeType !== 1)`. –  May 19 '11 at 21:57
  • Copy ....Thanks a lot its working great! Thanks for helping me out to solve this issues..:) – dinah May 19 '11 at 22:23
1

so i havent completely gotten the logic you are trying to get here. But if you want to tell if the checkbox was unchecked or checked you can test it like this

 function hideOrShowStuff(box, controlToHide1) {
   if(box.checked) {
     // the hide logic
   } else {
    // the show logic
   }
 }

you also need to pass in the box reference like this

 onclick="HideOrShowStuff(this, 1)" 

hope that helps

megakorre
  • 2,213
  • 16
  • 23
  • ok, i got on how to check/unchecked or hide/show when one checkbox is checked but what im looking for is when I have 5 checkboxes Fastfood, Catering, Carryout, Delivery and Bar when user clicked Fastfood ,rest checkboxes are disable, when user checked Catering, rest are disable but when user checked Carryout only Fastfood and Catering are disable. Then when user unchecked, all checkboxes back to enable/show. thanks! – dinah May 19 '11 at 18:56
0

Try this code

 <script>
            function uncheck0(){
                for(var ii=1; ii<=3; ii++){
                    if(document.getElementById("q6_"+ii).checked==true){
                       document.getElementById("q6_"+ii).checked=false;
                    }
                }
            }
            function uncheck(id, from, to){
                for(var ii=from; ii<=to; ii++){
                    if(document.getElementById(id+ii).checked==true){
                       document.getElementById(id+ii).checked=false;
                    }
                }
            }
        </script>
Symfony
  • 2,289
  • 6
  • 23
  • 30
0

js fiddle demo

function changeCheckBox() {
     try {

         var max = document.mainForm.serNo.length;
         var count = 0;

         for (var i = 0; i < max; i++) {
             if (document.mainForm.serNo[i].checked == true) {
                 count++;
                 serNoChecked = i;
             }
         }
         if (count == 1) {
             for (var i = 0; i < max; i++) {
                 if (document.mainForm.serNo[i].checked == false) {
                     document.mainForm.serNo[i].disabled = true;
                 }
             }
         } else if (count == 0) {
             for (var i = 0; i < max; i++) {
                 document.mainForm.serNo[i].disabled = false;
             }
         }

         if (null == max) return false;
         if (count == 0) {
             return true;
         } else if (count > 0) {
             return false;
         }

     } catch (e) {
         alert(e.message);
     }
 }



<form  name="mainForm" method="GET" action="Controller">
<TD STYLE="width:10px">
    <input type="checkbox" id="serNo" name="serNo" value="" onclick="changeCheckBox()" />
    <input type="checkbox" id="serNo" name="serNo" value="" onclick="changeCheckBox()" />
    <input type="checkbox" id="serNo" name="serNo" value="" onclick="changeCheckBox()" />
</TD>
</form>
shareef
  • 9,255
  • 13
  • 58
  • 89
0

You could use jQuery for this it would (probably) make your life easier. Check out these articles on how to achieve what you want (using jQuery):

USING JQUERY TO SHOW/HIDE FORM ELEMENTS BASED ON A CHECKBOX SELECTION

Checkboxes + Jquery hide/show

NB: Other frameworks are available. Take your pick according to personal tastes.

Community
  • 1
  • 1
Ira Rainey
  • 5,173
  • 2
  • 34
  • 42
  • 3
    You shouldn't use JQuery if you ever want to know how Javascript actually works, though - maybe the OP wants to learn? – James May 19 '11 at 15:06
  • 1
    No he should use Dojo or YUI or Ender.js or ext3 or vanilla js or whatever framework suits this. Just because jquery exists doesn't mean it's the answer. – Incognito May 19 '11 at 15:06
  • 1
    This is far too simple for jQuery, I think. Setting DOM properties isn't very difficult. –  May 19 '11 at 15:08
  • 1
    Easy... I didn't say it was the only answer, I just said it would make it easier than the code he had. I'll amend the answer to make that more clear. Easier as in shorter, and easier to manage, plus being more likely to be cross-browser compatible. – Ira Rainey May 19 '11 at 15:09
  • 1
    Wow, marked down for mentioning jQuery. I'll wash my mouth out with soap. While jQuery isn't the only framework on the block, and subjectively it could be argued it's not the best, if you're building web apps then it can be a good choice for many. Yes jQuery is only JS in a wrapper, and yes sometimes plain ole JS is easy enough for the job, but if you've got a whole web app to build then using a framework from the off, for the big and little things alike makes sense. – Ira Rainey May 19 '11 at 15:16
0

Using a framework or toolkit (like jQuery) will make life easier, but it's probably best to learn how the manipulate the DOM with javascript before moving on to a toolkit. Like learning to add before using a calculator.

The best way to deal with this is to look at the state of your checkboxes. if(document.myform.box2.checked == true), then make decisions based on the state of your checkboxes. The function you have above simply modifies the checkboxes without knowing anything about their state. It would be better to just pass (this) to the function, and then walk the DOM. "this" would be the checkbox when it comes into the function as a parameter. So your function would say "okay, I've got checkbox "1" passed to me, now what is the state of my other checkboxes?".