How do I validate the radio input of my code?

Asked

Viewed 1,982 times

1

$(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>
<input type="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">

  • Where the HTML code of these "c elements"?

  • <type="text" id="C1" placeholder="Name" class="box"> <br><br> <input type="text" id="C2" placeholder="Age" class="box" ><br> <input type="text" id="C3" placeholder="Phone" class="box"><br><br> <input type="password" id="C4" placeholder="Password" class="box"><br><br>

4 answers

2

Include a new else if at least 1 validation radio was checked out:

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

Small optimization

Your code has some repeated things that can be optimized, 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 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>
<input type="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">

1

I saw that you are using several if-lse to perform exactly the same thing, as there is no variation, I decided to use the function each, which receives a function such as callback to be applied in on all elements possessing the class caixa.

Instead of performing a return in each check, I created a flag beginning in 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>
<input type="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">

Obs.: I used the reply of @?vıas a basis

1

Óra, why don’t you just use HTML for this? The only requirement of its validation is that the field has some value (text type ones) or that it has been selected (choice ones), this is easily solved with the attribute required HTML5:

<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 attribute pattern is able to solve.

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 ":checked property".

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>
<input type="radio" name="sexo" value="masculino" /> Masculino <br />
<input type="radio" name="sexo" value="feminino" /> Femino <br />

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

  • But why on the radio click? I think the intention is to validate when sending the form

Browser other questions tagged

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