How to stop the $ .each cycle

0

Greetings, I have a table with inputs these are dynamic what I need is to validate them so that they are not empty at the time of recording them in the bd , these elements are traversed by means of a $.each in jquery , the problem is that the cycle has to end at the time it finds an empty field I tried with return false , break and even with return true but the cycle continues and this prevents you from doing the focus to the element empty, this code extract is called when you click on a button.

Jquery

if($(".hatrabajado:checked").val()==0){
        $('#historialTrabajo #bodyhisto tr').each(function () {
            var anios = $(this).find(".anios")
            var aniodura = $(this).find(".aniodura")
            var mdura = $(this).find(".mdura")
            if(anios.val()==""){
                anios.addClass("error")
                anios.focus()
                return false;//deberia  salir del ciclo
            }
            if(aniodura.val()==""){
                aniodura.addClass("error")
                aniodura.focus()
                return false;
            }
            if(mdura.val()==""){
                mdura.addClass("error")
                mdura.focus()
                return false;
            }
        })

    }
    
asked by Kevin 23.10.2017 в 20:18
source

1 answer

1

Try to define a variable outside the loop, and return the returns in the if inside the loop.

Like this:

if($(".hatrabajado:checked").val()==0){
  var x = true; //==> valor por defecto de return
  $('#historialTrabajo #bodyhisto tr').each(function () {
    var anios = $(this).find(".anios")
    var aniodura = $(this).find(".aniodura")
    var mdura = $(this).find(".mdura")
    if(anios.val()==""){
      anios.addClass("error")
      anios.focus()
      return x = false;//deberia  salir del ciclo
    }
    if(aniodura.val()==""){
      aniodura.addClass("error")
      aniodura.focus()
      return x = false;
    }
    if(mdura.val()==""){
      mdura.addClass("error")
      mdura.focus()
      return x = false;
    }
  })
  return x;
}
    
answered by 23.10.2017 в 21:30