How do I validate the radio input of my code?

0

$(function() {

  $("#btn").click(function() {

    $("#c1").css("background-color", "white");
    $("#c2").css("background-color", "white");
    $("#c3").css("background-color", "white");
    $("#c4").css("background-color", "white");

    /// validação 
    if ($("#c1").val() == "") {
      alert("preencha os campos!!");
      $("#c1").css("background-color", "red");
      return false;

    } else if ($("#c2").val() == "") {
      alert("preencha os campos!!");
      $("#c2").css("background-color", "red");
      return false;

    } else if ($("#c3").val() == "") {
      alert("preencha os campos!!");
      $("#c3").css("background-color", "red");
      return false;
    } else if ($("#c4").val() == "") {
      alert("preencha os campos!!");
      $("#c4").css("background-color", "red");
      return false;
    }

    return true;

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="c1" placeholder="Nome" class="caixa"> <br><br>
<input type="text" id="c2" placeholder="Idade" class="caixa"><br><br>
<input type="text" id="c3" placeholder="Telefone" class="caixa"><br><br>
<input type="password" id="c4" placeholder="Senha" class="caixa"><br><br> M:

<input type="radio" name="sexo" value="masculino" id="r1"><br><br> F:
<input type="radio" name="sexo" value="feminino" id="r2"><br><br> Salvar login :<input type="checkbox"><br><br> Menssagem de texto das novidades :<input type="checkbox"><br><br><br>

<input type="button" id="btn" value="entrar">
    
asked by anonymous 01.12.2017 / 20:07

4 answers

2

Include a new else if in validation that checks if at least 1 radio has been checked:

else if(!$("input[name='sexo']:checked").length){
    alert("Marque M ou F");
    return false;
}

Small optimization

Your code has some repeatable things you can optimize, one of them is these lines:

$("#c1").css("background-color", "white");
$("#c2").css("background-color", "white");
$("#c3").css("background-color", "white");
$("#c4").css("background-color", "white");

Since all the fields have the same class .caixa , it is better to use only 1 line to change the background of all of them:

$(".caixa").css("background-color", "white");

$(function() {
   $("#btn").click(function() {
      $(".caixa").css("background-color", "white");

      /// validação 
      if ($("#c1").val() == "") {
      alert("preencha os campos!!");
      $("#c1").css("background-color", "red");
      return false;
      } else if ($("#c2").val() == "") {
      alert("preencha os campos!!");
      $("#c2").css("background-color", "red");
      return false;
      } else if ($("#c3").val() == "") {
      alert("preencha os campos!!");
      $("#c3").css("background-color", "red");
      return false;
      } else if ($("#c4").val() == "") {
      alert("preencha os campos!!");
      $("#c4").css("background-color", "red");
      return false;
      } else if(!$("input[name='sexo']:checked").length){
      alert("Marque M ou F");
      return false;
      }

      alert("Formulário validado!");
      return true;
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="c1" placeholder="Nome" class="caixa"> <br><br>
<input type="text" id="c2" placeholder="Idade" class="caixa"><br><br>
<input type="text" id="c3" placeholder="Telefone" class="caixa"><br><br>
<input type="password" id="c4" placeholder="Senha" class="caixa"><br><br> M:
<input type="radio" name="sexo" value="masculino" id="r1"><br><br> F:
<input type="radio" name="sexo" value="feminino" id="r2"><br><br> Salvar login :<input type="checkbox"><br><br> Menssagem de texto das novidades :<input type="checkbox"><br><br><br>
<input type="button" id="btn" value="entrar">
    
02.12.2017 / 00:37
1

I saw that you are using several if-else to do exactly the same thing, since there is no variation, I decided to use the each function, which receives a function like callback to be applied to all the elements that have the class caixa .

Instead of doing return on each check, I created a flag starting at true , if any field was invalid, it is set to false

$(function() {
   $("#btn").click(function() {
      var valido = true;
      $(".caixa").css("background-color", "white");
      $(".caixa").each(function() {
        if(this.value == "") {
          $(this).css("background-color", "red");
          valido = false;
        }
      });
      
      if(!$("input[name='sexo']:checked").length){
         alert("Marque M ou F");
         valido =  false;
      }
      
      if (valido) {
        alert("Formulário validado!");
        return valido;
      }
      alert("preencha os campos!!");
      return valido;
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="c1" placeholder="Nome" class="caixa"> <br><br>
<input type="text" id="c2" placeholder="Idade" class="caixa"><br><br>
<input type="text" id="c3" placeholder="Telefone" class="caixa"><br><br>
<input type="password" id="c4" placeholder="Senha" class="caixa"><br><br> M:
<input type="radio" name="sexo" value="masculino" id="r1"><br><br> F:
<input type="radio" name="sexo" value="feminino" id="r2"><br><br> Salvar login :<input type="checkbox"><br><br> Menssagem de texto das novidades :<input type="checkbox"><br><br><br>
<input type="button" id="btn" value="entrar">

Note: I used the response of @ ÐvÐ as a basis

    
02.12.2017 / 01:00
1

Ow, why do not you just use HTML for this? The only requirement of your validation is that the field has some value (in the type of text) or that has been selected (in those of choice), this is easily solved with the attribute #

<form action='/foo' method='post'>
  <label for='male'>Masculino</label>
  <input id='male' type='radio' name='sex' required>
  
  <label for='female'>Feminino</label>
  <input id='female' type='radio' name='sex'>
  
  <button type='submit'>Enviar</button>
</form>

It may make more sense to use Javascript for complex validations, which do not even use the required is able to solve.

    
02.12.2017 / 01:20
0

You need to assign the same name to the radio. As if they were part of the same field. Then you access the value using the property: checked.

Example:

$('input[name=sexo]').on('click', function() {
  var valorDoRadio = $('input[name=sexo]:checked').val();
  alert(valorDoRadio); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="radio" name="sexo" value="masculino" /> Masculino <br />
<input type="radio" name="sexo" value="feminino" /> Femino <br />

With the value in hand, you can validate as you wish.

    
01.12.2017 / 21:19