How to make a checkbox not selected if there is no previous checkbox selected?

0

I have a pile of monthly payments, where each one is found in a select.

I'd like all of them to be disabled first except the first check, and that by enabling the first check, the second check might be available to be enabled, and if I disable the first check, the second check is unavailable again (disable) to be enabled, and so on.

In other words, I can only select a checkbox if the previous chekbox is selected

I would like to do this with pure jquery or php or with other suggestions.

<input type="checkbox" > Janeiro
<input type="checkbox" > Fevereiro
<input type="checkbox" > Março
<input type="checkbox" > Abril'
    
asked by anonymous 18.10.2018 / 19:29

1 answer

2

A function can be made to click on a checkbox check if it is checked, if it is enabled next, otherwise disable the next one and uncheck it even disabled.

Initially it is best to leave only the first one enabled in HTML .

$(".meses").click(function(){
  let meses = document.querySelectorAll(".meses");
  for (let i = 0; i < meses.length; i++) {
    if (meses[i].checked && i+1 < meses.length){
      meses[i+1].removeAttribute("disabled");
    } else {
      if (i+1 < meses.length) {
        for (let j = i+1; j < meses.length; j++) {
          meses[j].checked = false;
          meses[j].setAttribute("disabled", "true");
        }
      }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><inputclass="meses" value="1" type="checkbox">Janeiro
<input class="meses" value="2" type="checkbox" disabled="disabled">Fevereiro
<input class="meses" value="3" type="checkbox" disabled="disabled">Março
<input class="meses" value="4" type="checkbox" disabled="disabled">Abril
    
18.10.2018 / 20:28