0

I have 5 checkboxes, I want to tick 1 checkbox then the other 4 checkboxes will disable to tick, if I untick the 1 checkbox, the other 4 checkboxes will able to tick. Hope someone can guide me on how to solve it based on my below the coding:

<div class="form-group" id="taraf_keselamatan_fail">
<label for="cp1" class="control-label col-lg-4">Taraf Keselamatan Fail:</label>
<div class="col-lg-3">
<input type="checkbox" name="rahsia_besar" id="rahsia_besar" value="1"><b> Rahsia Besar</b></input>&nbsp;&nbsp;&nbsp;
<input type="checkbox" name="rahsia" id="rahsia" value="1"><b> Rahsia</b></input>&nbsp;&nbsp;&nbsp;
<input type="checkbox" name="sulit" id="sulit" value="1"><b> Sulit</b></input>&nbsp;&nbsp;&nbsp;<br>
<input type="checkbox" name="terhad" id="terhad" value="1"><b> Terhad</b></input>&nbsp;&nbsp;&nbsp;
<input type="checkbox" name="terbuka" id="terbuka" value="1"><b> Terbuka</b></input>&nbsp;&nbsp;&nbsp;
</div>
</div>

Now my output result like below the picture can tick all the checkboxes:

output 1

My expected result like below the sample picture, just can tick 1 box in the checkbox. enter image description here

This is my try the coding in the javascript, but it cannot work:

<script>
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 "rahsia_besar":
            blacklist = ["rahsia", "sulit","terhad","terbuka"];
            break;
            case "rahsia":
            blacklist = ["rahsia_besar", "sulit","terhad","terbuka"];
            break;
            case "sulit":
            blacklist = ["rahsia_besar", "rahsia","terhad","terbuka"];
            break;
            case "terhad":
            blacklist = ["rahsia_besar", "rahsia","sulit","terbuka"];
            break;
            case "terbuka":
            blacklist = ["rahsia_besar", "rahsia","sulit","terhad"];
            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 = "";
        }
    }   
}


</script>
4
  • Can you show us some code you've tried so far? This feels like you're just asking someone to write the whole solution for you Commented Dec 9, 2020 at 9:37
  • 4
    May I ask why you are trying to modify a checkbox to act as a radio button instead of using a radio button? Commented Dec 9, 2020 at 9:41
  • I have updated the code for javascript, kindly to check. Thanks. Commented Dec 9, 2020 at 9:41
  • @PiNetworkCrytocurrency ... there are two approaches ... one covering exactly your described use case, the other one almost covering it with no additional scripting needed. Have a look at the answer(s) of mine. Commented Dec 9, 2020 at 13:46

2 Answers 2

1

The intended behavior does (almost ... see EDIT) not need any form of additional scripting for one gets such a behavior for free with any radio group ...

// scripting is just for proofing the behavior of a radio group/collection

function logCurrentlyCheckedFailValue(evt) {
  if (evt.target.type === 'radio') {

    console.log(`radio name: ${ evt.target.name }\nradio value: ${ evt.target.value }`);
  }
}

function mainInit() {
  document
    .querySelector('#taraf_keselamatan_fail')
    .addEventListener('click', logCurrentlyCheckedFailValue)
}
mainInit();
.as-console-wrapper { max-height: 60%!important; }
<form>
  <fieldset class="form-group" id="taraf_keselamatan_fail">

    <legend class="control-label col-lg-4">Taraf Keselamatan Fail:</legend>
    <div class="col-lg-3">
      <label>
        <input type="radio" name="taraf_keselamatan_fail" value="rahsia_besar"/>
        <b>Rahsia Besar</b>
      </label>
      <label>
        <input type="radio" name="taraf_keselamatan_fail" value="rahsia"/>
        <b>Rahsia</b>
      </label>
      <label>
        <input type="radio" name="taraf_keselamatan_fail" value="sulit"/>
        <b>Sulit</b>
      </label>
      <label>
        <input type="radio" name="taraf_keselamatan_fail" value="terhad"/>
        <b>Terhad</b>
      </label>
      <label>
        <input type="radio" name="taraf_keselamatan_fail" value="terbuka"/>
        <b>Terbuka</b>
      </label>
    </div>

  </fieldset>
</form>

EDIT

I want to apologize to the OP because of me not reading the question carefully enough. The OP's use case indeed is distinct from what a radio group actually does offer.

Here we go ...

function setControlStateViaBoundConfig(elm) {
  const config = this;
  if (elm !== config.ignore) {

    elm.checked = config.checked;
    elm.disabled = config.disabled;
  }
}
function toggleBehaviorOfFailureOptions(evt) {
  const targetElement = evt.target;

  if (targetElement.type === 'checkbox') {
    const isDisableOthers = targetElement.checked;

    evt.currentTarget // equals element with `id="taraf_keselamatan_fail"`
      .querySelectorAll('[type="checkbox"]')
      .forEach(setControlStateViaBoundConfig, {

        ignore: targetElement,
        checked: false,
        disabled: isDisableOthers,
      });
  }
}

function mainInit() {
  document
    .querySelector('#taraf_keselamatan_fail')
    .addEventListener('click', toggleBehaviorOfFailureOptions)
}
mainInit();
[type="checkbox"]:disabled + b { opacity: .4; }

.as-console-wrapper { max-height: 60%!important; }
<form>
  <fieldset class="form-group" id="taraf_keselamatan_fail">

    <legend class="control-label col-lg-4">Taraf Keselamatan Fail:</legend>
    <div class="col-lg-3">
      <label>
        <input type="checkbox" name="rahsia_besar" value="1"/>
        <b>Rahsia Besar</b>
      </label>
      <label>
        <input type="checkbox" name="rahsia" value="1"/>
        <b>Rahsia</b>
      </label>
      <label>
        <input type="checkbox" name="sulit" value="1"/>
        <b>Sulit</b>
      </label>
      <label>
        <input type="checkbox" name="terhad" value="1"/>
        <b>Terhad</b>
      </label>
      <label>
        <input type="checkbox" name="terbuka" value="1"/>
        <b>Terbuka</b>
      </label>
    </div>

  </fieldset>
</form>

Sign up to request clarification or add additional context in comments.

Comments

0

I created a Stackblitz from you code extract and it is working, could you please check if this is what you expected as solution ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.