0

!hello,

i have a number of checkboxes generated with PHP. There is a validation button. I want to prevent the user to valid the form without checking at least 1 checkbox.

I have this code

var checkboxes = document.getElementsByName('date[]');
var btn = document.getElementById('Submit');
date.onchange = function(){
   for (var i=0;i<checkboxes.length;i++)
   {
      if(checkboxes[i].checked)
      {
         btn.disabled = false;
      } 
      else 
      {
         btn.disabled = true;
      }
   }
}
<form>
....
<table>
    <tr id="{{ cpt }}">
        <td><input type="checkbox" class="date" id="date" name="date[]"
                            checked value="{{ jdv.day }}"></td>
        <td>{{ jdv.day }}</td>
   </tr>
</table> 
</form>

But it only work for the first checkbox!

can you help me?

Thanks

ramsey_lewis
  • 558
  • 8
  • 25

3 Answers3

0

Your script will set button.disabled = true; for every checkbox that is unchecked... that means if you check any box than the last, this will always set disabled to true in the end.

add this to your function after btn.disabled = false;

return true;

resulting in this code:

var checkboxes = document.getElementsByName('date[]');
var btn = document.getElementById('Submit');
date.onchange = function(){
   for (var i=0;i<checkboxes.length;i++)
   {
      if(checkboxes[i].checked)
      {
         btn.disabled = false;
         return true;
      } 
      else 
      {
         btn.disabled = true;
      }
   }
}

this will stop your function once it detects the first checked checkbox and prevent the following ones from overriding the disabled property of your button.

Merlin Denker
  • 1,380
  • 10
  • 15
-1

You'd better do some counter which'll count checked checkboxes and in the end compare it with number of minimum num of checked checkboxes

desu
  • 455
  • 2
  • 18
-1

you should keep a variable, avoiding that other checkboxes results override each other.

Something like:

var toShow = true;
var checkboxes = document.getElementsByName('date[]');
var btn = document.getElementById('Submit');
date.onchange = function(){
for (var i=0;i<checkboxes.length && toShow;i++) {
    if(!checkboxes[i].checked)
    {
         toShow = false;
    }
}
if(toShow)
    btn.disabled = false;
} else 
{
    btn.disabled = true;
}
  • The first unchecked checkbox will set toShow to false, stop the loop and set the button to disabled. That means if any following checkbox is checked it will be ignored. – Merlin Denker May 16 '14 at 13:59
  • Thanks, i just tried it but it doesn't work :(. Nothing happens when i click in the checkboxes. My button isn't disable – ramsey_lewis May 16 '14 at 14:16
  • Oh, sorry .. I followed your code and now I see that the idea isnt' that. You should invert the idea. Set "toShow = false" and "if(checkboxes[i].checked) -> toShow = true" This will make that, if at least one is checked, it enables the button. (and put !toShow in the while) Hugs – DropDaCode May 16 '14 at 14:52