Checking out checkbox

Asked

Viewed 51 times

-1

Good afternoon.

I need some help. I’m creating an Html5 form for my college work. I need to check if at least 1 checkbox item is marked so that it is possible to send the data.

I tried using if and did not succeed, the same happened with trying to use for.

I am using pure JS for validation.

<div class="campo">
                <label>Áreas de interesse</label>
                <label>
                    <input type="checkbox" name="interesse" value="sim"> Análise
                </label>
                <label>
                    <input type="checkbox" name="interesse" value="sim"> Banco de dados
                </label>
                <label>
                    <input type="checkbox" name="interesse" value="sim"> Desenvolvimento
                </label>
                <label>
                    <input type="checkbox" name="interesse" value="sim"> Redes de computadores
                </label>
                <label>
                    <input type="checkbox" name="interesse" value="sim"> Engenharia de Software
                </label>
            </div>

Script I tried:

for

In this case it only sends the data if all the options are checked.

for (var i=0;i<interesse.length;i++) { 
                if (interesse[i].checked == true) { 
                    vInteresse = true;
                }  
                else {
                    alert("Escolha pelo menos uma área de interesse!");
                    event.preventDefault();
                    document.getElementsByName('interesse').focus();
                    return false;
                }
            }

The if Else, tried with each checkbox a different name, I did basically like this:

In that case any option I’d set would give Else’s message.

if (analise==true || dba==true || dev==true || redes==true || engineer==true) {
  vInteresse = true;
} else {
  alert("Escolha pelo menos uma área de interesse!");
  event.preventDefault();
  document.getElementsByName('interesse').focus();
  return false;
}

  • 1

    Vale [Edit] the question to include the Javascript code you tried to do, as well as a more detailed explanation of what did not work.

  • Thanks for the tip. I think it’s now a little easier to understand.

1 answer

0

can try something like:

      function validaCheckboxes() {
        const checkboxes = document.querySelectorAll("input[name='interesse'");
        let valid = false;
        checkboxes.forEach(check => {
          if (check.checked) {
            valid = true;
          }   
        }); 
        alert(valid ? 'Valido' : 'Invalid');
      } 

This function will search for all inputs as name="interesse" and analyze whether the property checked of them is true, and will give you a alert saying if any the condition Voce described this validates or not. Basing on this function only treat the result as you want :)

  • Jose, in parts it worked. Thank you very much.. But I needed that in place of this Alert showing whether it was valid or invalid, I would have to show only one Alert if no option was checked. If true, only an msg of sent data would appear, which is in another if, at the end of the script.

  • You can change the function to return true or false and do all validation on its "Submit" function (I think it should be where your other if is), the Alert was to illustrate the use :)

  • 1

    I got it here Jose, thank you very much man. I left everything in the same function to validate. Thank you very much!!

  • Another question. If no option is checked, how do I select the first checkbox and radio option for Focus ?

  • You can use the document.querySelector("input[name='interesse']").focus() querySelector selects some of the first he finds

Browser other questions tagged

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