Search code examples
javascripthtmlcheckboxradio-button

How to switch between checkboxes and radio buttons JavaScript


I have this code where I am creating some questions. My question looks like this:

enter image description here

My problem is that at these options I have made checkboxes. Although when the "Multiple Answers" button is turned off I want to make the user have 1 option maximum. So I imagine that I have to convert these checkboxes into radio buttons. I don't know if there is an easier way to do this.

Does anyone know how can I change my code so that if let's say var allowMultipleAnswers = true to be able to select more than one options, but when it is false to be able to choose only 1 option.

This is my function where I create options:

function newOption(parentDiv) {
  var buttonId = 2;
  var numberOfThisOption = 1;
  var optionText = "Option ";

  var optionDiv = document.createElement("div");
  optionDiv.className = "mb-3 option row";
  /***************************************** */
  var button = document.createElement("input");
  button.className = "col-1 offset-1 buttonForOption";
  button.setAttribute("type", "checkbox");
  button.setAttribute("style", "flex-basis: 2% !important;");

  button.id = buttonId;
  optionDiv.appendChild(button);
  /***************************************** */
  var label = document.createElement("label");
  label.className = " ml-4 col-6 labelForOption text-left";
  // label.setAttribute("for", buttonId);
  label.setAttribute(
    "style",
    "margin-bottom: 0rem !important; border: solid 1px; border-color: #d6d6d6;  padding-left: 10px !important; border-radius: 3px; width: 90%"
  );
  optionDiv.appendChild(label);
  /***************************************** */
  var actualText = document.createElement("span");
  actualText.className = "textForOption";
  label.setAttribute("contenteditable", "true");
  actualText.textContent = optionText + numberOfThisOption;
  label.appendChild(actualText);
  /***************************************** */

  parentDiv.appendChild(optionDiv);
}

Solution

  • Sure. Just pass in a boolean true to not make radios and remember to give a name

    function newOption(parentDiv,allowMultipleAnswers) {
    
      var button = document.createElement("input");
      button.className = "col-1 offset-1 buttonForOption";
      button.setAttribute("type", allowMultipleAnswers  ? "checkbox" : "radio");
      button.setAttribute("style", "flex-basis: 2% !important;");
      button.id = buttonId;
      button.name = buttonId;
      optionDiv.appendChild(button);
    

    To toggle them all, try

      parentDiv.querySelectorAll(".buttonForOption")
        .forEach(button => button.type = allowMultipleAnswers ? "checkbox" : "radio");