Home > Software engineering >  Button not being enabled after click on checkboxes
Button not being enabled after click on checkboxes

Time:11-06

So, I have created a table with checkboxes and I want the user to check at least two options in order to enable the button to submit the answers.

HTML

 <body>
        <h1>Checked two options</h1>
        <br/>
        <p>What are some of your favorite dishes?</p>
        <table id="tblFoods">
            <tr>
                <td><input id="chkPizza" type="checkbox" /><label for="chkPizza">Pizza</label></td>
            </tr>
            <tr>
                <td><input id="chkLasagna" type="checkbox" /><label for="chkLasagna">Lasagna</label></td>
            </tr>
            <tr>
                <td><input id="chkPasta" type="checkbox" /><label for="chkPasta">Pasta</label></td>
            </tr>
            <tr>
                <td><input id="chkBarbecue" type="checkbox" /><label for="chkBarbecue">Barbecue</label></td>
            </tr>
        </table>
        <br />
        <input type = "submit" id="mybtn"  disabled value = "Submit" onclick = "EnableButton()"/>

    </body>

And I have this function, but it's not working. I'm using a looping to count how many options have been checked by the user, but it doesn't work.

JS

function EnableButton()
{
   var tblFoods = document.getElementById("tblFoods");
   var checkeds = tblFoods.getElementsByTagName("INPUT");

   var counter = 0;

   for(let i =0; i < checkeds.length;i  )
   {
       if(checkeds[i].checked)
       {
        counter  ;
       }
   }

   if(counter>=2)
   {
       document.getElementById("mybtn").disabled = false;
   }
   else
   {
       document.getElementById("mybtn").disabled = true;
   }
}

What am I doing wrong?

CodePudding user response:

You need to call your Enable function when you check boxes. Here's a working example: https://codesandbox.io/s/proud-architecture-ou5l2?file=/src/index.js

using your existing code:

var tblFoods = document.getElementById("tblFoods");
var checkeds = tblFoods.querySelectorAll("input");
const btn = document.getElementById("mybtn");

function enableButton() {
  var counter = 0;

  for (let i = 0; i < checkeds.length; i  ) {
    if (checkeds[i].checked) {
      counter  ;
    }
  }

  if (counter >= 2) {
    btn.disabled = false;
  } else {
    btn.disabled = true;
  }
}

const handleClick = () => {
  enableButton();
  // do whatever else you need in here
};

checkeds.forEach((box) => box.addEventListener("click", handleClick));

CodePudding user response:

You need to check for whether the button needs to be enabled when the inputs get checked, not when the button gets clicked.

The nicest, most concise way to do this is:

const table = document.querySelector('#tblFoods');
table.addEventListener('change', () => {
  const checkedCount = [...table.querySelectorAll('input')].reduce((a, input) => a   input.checked, 0);
  document.getElementById("mybtn").disabled = checkedCount < 2;
});
<h1>Checked two options</h1>
<br/>
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
  <tr>
    <td><input id="chkPizza" type="checkbox" /><label for="chkPizza">Pizza</label></td>
  </tr>
  <tr>
    <td><input id="chkLasagna" type="checkbox" /><label for="chkLasagna">Lasagna</label></td>
  </tr>
  <tr>
    <td><input id="chkPasta" type="checkbox" /><label for="chkPasta">Pasta</label></td>
  </tr>
  <tr>
    <td><input id="chkBarbecue" type="checkbox" /><label for="chkBarbecue">Barbecue</label></td>
  </tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Your original code, tweaked, works too, but is pretty verbose in comparison.

document.querySelector('#tblFoods').addEventListener('change', () => {
   var tblFoods = document.getElementById("tblFoods");
   var checkeds = tblFoods.getElementsByTagName("INPUT");

   var counter = 0;

   for(let i =0; i < checkeds.length;i  )
   {
       if(checkeds[i].checked)
       {
        counter  ;
       }
   }

   if(counter>=2)
   {
       document.getElementById("mybtn").disabled = false;
   }
   else
   {
       document.getElementById("mybtn").disabled = true;
   }
});
<h1>Checked two options</h1>
<br/>
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
  <tr>
    <td><input id="chkPizza" type="checkbox" /><label for="chkPizza">Pizza</label></td>
  </tr>
  <tr>
    <td><input id="chkLasagna" type="checkbox" /><label for="chkLasagna">Lasagna</label></td>
  </tr>
  <tr>
    <td><input id="chkPasta" type="checkbox" /><label for="chkPasta">Pasta</label></td>
  </tr>
  <tr>
    <td><input id="chkBarbecue" type="checkbox" /><label for="chkBarbecue">Barbecue</label></td>
  </tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" />
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You have to run your function when the user select the food, not when the user click the button. A simple solution is removing the onclick event from the button and adding the onchange event in every input:

<h1>Checked two options</h1>
  <br />
  <p>What are some of your favorite dishes?</p>
  <table id="tblFoods">
    <tr>
      <td><input id="chkPizza" type="checkbox" onchange="EnableButton()" /><label for="chkPizza">Pizza</label></td>
    </tr>
    <tr>
      <td><input id="chkLasagna" type="checkbox" onchange="EnableButton()" /><label for="chkLasagna">Lasagna</label>
      </td>
    </tr>
    <tr>
      <td><input id="chkPasta" type="checkbox" onchange="EnableButton()" /><label for="chkPasta">Pasta</label></td>
    </tr>
    <tr>
      <td><input id="chkBarbecue" type="checkbox" onchange="EnableButton()" /><label for="chkBarbecue">Barbecue</label>
      </td>
    </tr>
  </table>
  <br />
  <input type="submit" id="mybtn" disabled value="Submit" />

CodePudding user response:

You could use something like:

document.querySelectorAll("input[type='checkbox']").forEach(e => e.addEventListener("click", () => {
  const submitButton = document.querySelector("#mybtn");
  if (!submitButton) return;
  
  const checkedInputs = document.querySelectorAll("#tblFoods input[type='checkbox']:checked").length;
  submitButton.disabled = checkedInputs < 2;
}));

In other words, every time a checkbox is clicked, a check is run on how many checkboxes are checked in total. If this amount is greater than or equal to two, the button is enabled, otherwise it is disabled.

CodePudding user response:

Maybe i am wrong but since u had initialized counter = 0, every time that the function its called, it will automatically set to 0, so u should declare it globally in order to be an effective counter.

var counter = 0;
    function EnableButton()
    {
       var tblFoods = document.getElementById("tblFoods");
        var checkeds = tblFoods.getElementsByTagName("INPUT");

   for(let i =0; i < checkeds.length;i  )
   {
       if(checkeds[i].checked)
       {
        counter  ;
       }
    }

  if(counter>=2)
 {
     document.getElementById("mybtn").disabled = false;
 }
 else
 {
     document.getElementById("mybtn").disabled = true;
 }

}

  • Related