How to validate 2 checkbox groups

Asked

Viewed 333 times

3

Personal in my form I have 2 distinct groups that have 4 checkbox each. The 1st group is already validated. Which is this: HTML with PHP, it loops with the amount of items in the database:

<?php
$select_funcao = "SELECT * FROM funcao ORDER BY nome";
$result_funcao = mysqli_query($conexao, $select_funcao);
    for ($i = 0; $i < mysqli_num_rows($result_funcao); $i++) {
        $linha_funcao = mysqli_fetch_array($result_funcao);
?>
        <div class="form-check">
            <label class="form-check-label" for="<?= $linha_funcao['codigo'] ?>">
            <input type="checkbox" class="form-check-input" id="<?= $linha_funcao['codigo'] ?>" name="funcao[]" value="<?= $linha_funcao['codigo'] ?>"><?php echo $linha_funcao['nome'] ?>
            </label>
        </div>
<?php
    }
?>

With that Script:

<script type="text/javascript">
function validar() {    
    var i = 0, counter = 0, funcao;
    funcao = document.forms[0].elements['funcao[]'];
        for (; i < funcao.length; i++) {
            if (funcao[i].checked) {
                    counter++;
                }
        }

    if (counter == 0) {
        alert("Selecione pelo menos uma função para essa questão!");
                return false;
        }
        return true;
}
</script>

These 1st checkbox validates right, no problems.

The point is I have another checkbox group:

HTML:

<input type="checkbox" name="correto[]" value="1" class="checkgroup" aria-label="Chebox para permitir input text">
<input type="checkbox" name="correto[]" value="2" class="checkgroup" aria-label="Chebox para permitir input text">
<input type="checkbox" name="correto[]" value="3" class="checkgroup" aria-label="Chebox para permitir input text">
<input type="checkbox" name="correto[]" value="4" class="checkgroup" aria-label="Chebox para permitir input text">

How to validate these above?

1 answer

2


You do not need to use as much code to check if a checkbox has been marked within a group. Only with...

var funcao = document.querySelector("[name='funcao[]']:checked");

...you can know if any checkbox with name='funcao[]' has been marked. If none has been marked will return null, then you can use a if(!funcao) which turns out to be funcao is null. Then you do the same thing with the other group name='correto[]'.

See how much simpler it is:

function validar() {    

   var funcao = document.querySelector("[name='funcao[]']:checked");
   var correto = document.querySelector("[name='correto[]']:checked");

   if(!funcao){
      alert("Selecione pelo menos uma função para essa questão!");
      return false;
   }

   if(!correto){
      alert("Selecione pelo menos uma opção!");
      return false;
   }

   return true;
}
<form>
   <div class="form-check">
      <label class="form-check-label" for="c1">
         <input type="checkbox" class="form-check-input" id="c1" name="funcao[]" value="c1">função 1
      </label>
   </div>
   <div class="form-check">
      <label class="form-check-label" for="c2">
         <input type="checkbox" class="form-check-input" id="c2" name="funcao[]" value="c2">função 2
      </label>
   </div>
   <br>
   Opções:
   <br>
   <input type="checkbox" name="correto[]" value="1" class="checkgroup" aria-label="Chebox para permitir input text">
   <input type="checkbox" name="correto[]" value="2" class="checkgroup" aria-label="Chebox para permitir input text">
   <input type="checkbox" name="correto[]" value="3" class="checkgroup" aria-label="Chebox para permitir input text">
   <input type="checkbox" name="correto[]" value="4" class="checkgroup" aria-label="Chebox para permitir input text">
</form>
<button onclick="validar()">Validar</button>

Learn to use the document.querySelector and the document.querySelectorAll which are very useful when selecting elements, as they accept CSS selectors which makes the task much more flexible and easy.

Docs:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.