Check Validation with jquery does not work for me

0

I have a page where I have N checkbox, of which at least one must be typed before submitting, I have the following but I do not validate check, someone knows why?

The JS code is:

<script type="text/javascript">
    $('form').submit(function (e) {
        if ($('input[type=checkbox]:checked').length === 0) {
            e.preventDefault();
            alert('Debe seleccionar al menos un valor');
        }
    });
</script>

In the picture you can see that the UI has the checks, I have the jquery files loaded and also shows the portion of code that should validate the checks.

    
asked by RSillerico 07.12.2016 в 20:57
source

4 answers

0

You need to add everything within $(document).ready() .

$(document).ready(function(){
  $('form').submit(function(e){

    if (!$("input:checkbox:checked").length){
      alert("No hay checkbox 'checked'");
    }
            e.preventDefault();
  });
});

JSBIN

    
answered by 07.12.2016 / 21:22
source
0
<script type="text/javascript">
  $(document).ready(function(){
    $('form').submit(function (e) {
         if($("input[type=checkbox]:checked").length != 0){
            //OK
         }else{
           alert('Debe seleccionar al menos un valor');
           return false;
         }
    });
   });
</script>
    
answered by 07.12.2016 в 21:18
0

Well at the end it's like this:

<script type="text/javascript">
    $(document).ready(function () {
        $('form').submit(function (e) {
            if ($("form").find("input:checkbox").length > 0) {
                if ($('input[type=checkbox]:checked').length === 0) {
                    e.preventDefault();
                    alert('Debe seleccionar al menos un valor');
                }
            }
        });
    });
</script>

and it works perfectly.

    
answered by 07.12.2016 в 23:25
0

This would be the optimized version: D

<script type="text/javascript">
  $(document).ready(function(){
    var $form = $('form');
    $form.on('submit', (function (e) {
        e.preventDefault(); // Si se va a enviar un AJAX
         if($form.find("input:checked").length > 0){
            //OK
         }
    });
   });
</script>

Why? because when saving the $ form in a variable, it will no longer search the entire DOM. As well as find, just look inside the chosen DOM, instead of the entire document.

And jquery recommends not using $('input[type=checkbox]:checked')

link

    
answered by 08.12.2016 в 21:29