Validate a Checkbox with JQuery

5

I would like to know how to validate a Checkbox with JQuery in a small form.

<form action="">
  <a>Correo: </a>
  <input type="email" name="correo">
  <br>
  <a>Telefono: </a>
  <input type="text" name="telefono">
  <br>
  <a>Aceptar condiciones: </a>
  <input type="checkbox" name="aceptar">
  <br>
  <button type="submit" id="submit">Enviar Formulario</button>
</form>

I found several types of validations .is(selector) and .prop() but I tried to apply them and I could not get it, I just want you to throw an alert that says something like Accepts the conditions .

    
asked by Eduardo Javier Maldonado 31.03.2016 в 21:19
source

4 answers

9

When you use is() you have to use the selector :checked :

$(document).ready(function() {
    $("#submit").on("click", function() {
        var condiciones = $("#aceptar").is(":checked");
        if (!condiciones) {
            alert("Debe aceptar las condiciones");
            event.preventDefault();
        }
    });
});
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
<form action="">
    <div>
        <p>Correo: </p>
        <input type="email" name="correo" id="correo">
    </div>
    <div>
        <p>Telefono: </p>
        <input type="text" name="telefono" id="telefono">
    </div>
    <div>
        <p>Aceptar condiciones: </p>
        <input type="checkbox" name="aceptar" id="aceptar">
    </div>
    <button type="submit" id="submit">Enviar Formulario </button>
</form>

When the conditions have not been marked you should use event.preventDefault() to prevent the form from making post .

    
answered by 31.03.2016 / 21:27
source
3

You could implement something like being

$(function(){
  $("#submit").click(function(event){
        var seleccion = $("#aceptar")[0].checked;
        if(!seleccion){
            event.preventDefault();
            alert("Acepta las condiciones");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<form action="">
<a>Correo: </a><input type="email" name="correo"><br>
<a>Telefono: </a><input type="text" name="telefono"><br>
<a>Aceptar condiciones: </a><input type="checkbox" name="aceptar" id="aceptar" ><br>
<button type="submit" id="submit">Enviar Formulario </button>
</form>

There are also other alternatives such as being

var seleccion = $("#aceptar").is(':checked');
    
answered by 31.03.2016 в 21:27
2

Just ask if you are checking with .is(':checked') :

$('form').on('submit', function(){
    if($("input[type='checkbox']").is(':checked') === true)
    console.log('Soy valido')
  else{
  console.log('Soy invalido')
    return false; //Soy invalid
  } 
})

Live DEMO

    
answered by 31.03.2016 в 21:30
1

You can use "required" and thus you do not have to use JavaScript, although the message shown will depend on the browser.

<input type="checkbox" name="aceptar" required>

    
answered by 31.03.2016 в 21:43