Validate a radio input with a loop for inside another loop if [closed]

1

... and make it work: leaving the radius in null, you should skip the alert. But it does not and validates.

else if(false){     

        function check(){

            var r= document.getElementsByName("e");
            var e= -1;

            for(var i=0; i < r.length; i++){
                if(r[i].checked>=0){
                    e = i; 
                }
            }

            if (e>=0){                  
                return true;
            }

        }
            alert("Error: selecciona alguna opción");       
    }

I do not know what I have to put exactly in the condition of the else if it works.

Thanks in advance.

    
asked by Nian_cat 20.02.2016 в 01:22
source

1 answer

1

Your code and logic are fine, but it turns out that the checked property is not a numeric type, but rather a Boolean type.

$(document).ready(function() {
  $('#validar').click(function() {
    if (!check()) {
      alert('Debe seleccionar por lo menos una opción');
    } else {
      alert('Validación cumplida');
    }
  });
});

function check() {

  var r = document.getElementsByName("e");
  var e = -1;

  for (var i = 0; i < r.length; i++) {
    if (r[i].checked == true) {
      e = i;
    }
  }

  if (e >= 0) {
    return true;
  }
  return false;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="checkbox" name="e" />
  <input type="checkbox" name="e" />
  <input type="checkbox" name="e" />
  <input type="checkbox" name="e" />
  <input type="checkbox" name="e" />
  <input type="checkbox" name="e" />
  <input type="checkbox" name="e" />
  <a href="#!" id="validar">Validar</a>
</form>
    
answered by 20.02.2016 в 03:18