2012-07-18 24 views
25

He usado this jquery complemento de validación para el siguiente formulario.Validar campos de entrada añadidos dinámicamente

<script src="http://code.jquery.com/jquery-latest.js"></script> 
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script> 

<script> 
    $(document).ready(function(){ 
     $("#commentForm").validate(); 
    }); 

    function addInput() { 
     var obj = document.getElementById("list").cloneNode(true); 
     document.getElementById('parent').appendChild(obj); 
    } 
</script> 

<form id="commentForm" method="get" action=""> 
    <p id="parent"> 
     <input id="list" class="required" /> 
    </p> 

    <input class="submit" type="submit" value="Submit"/> 
    <input type="button" value="add" onClick="addInput()" /> 
</form> 

Cuando se hace clic en el botón Agregar, se agrega dinámicamente una nueva entrada. Sin embargo, cuando se envía el formulario, solo se valida el primer campo de entrada. ¿Cómo puedo validar entradas añadidas dinámicamente? Gracias ...

+0

has necesitado '$ ('forma') en ('enviar', function (e) {$ (this) .validate() ; return false;}); ' – Krimo

+0

http://stackoverflow.com/a/26542591/5557983 Esta solución de @Stephen Muecke funcionó para mí –

Respuesta

26

Debe tener el atributo 'nombre' para sus entradas. Debe agregar las reglas dinámicamente, una opción es agregarlas cuando se envíe el formulario.

Y aquí es mi solución que he probado y funciona:

<script type="text/javascript"> 
    $(document).ready(function() { 
     var numberIncr = 1; // used to increment the name for the inputs 

     function addInput() { 
      $('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />')); 
      numberIncr++; 
     } 

     $('form.commentForm').on('submit', function(event) { 

      // adding rules for inputs with class 'comment' 
      $('input.comment').each(function() { 
       $(this).rules("add", 
        { 
         required: true 
        }) 
      });    

      // prevent default submit action   
      event.preventDefault(); 

      // test if form is valid 
      if($('form.commentForm').validate().form()) { 
       console.log("validates"); 
      } else { 
       console.log("does not validate"); 
      } 
     }) 

     // set handler for addInput button click 
     $("#addInput").on('click', addInput); 

     // initialize the validator 
     $('form.commentForm').validate(); 

    }); 


</script> 

Y forma parte html:

<form class="commentForm" method="get" action=""> 
    <div> 

     <p id="inputs">  
      <input class="comment" name="name0" /> 
     </p> 

    <input class="submit" type="submit" value="Submit" /> 
    <input type="button" value="add" id="addInput" /> 

    </div> 
</form> 

Buena suerte! ¡Por favor apruebe la respuesta si le conviene!

+2

Muchas gracias por su esfuerzo @Angel. Funcionó como magia. Trabajo increíble :) – Rav

+2

¡De nada! – Angel

+2

FWIW, puede llamar validar una vez en document.ready, y luego agregar sus reglas dentro de la función 'addInput'. Si desea mostrar que la validación es exitosa/fallida, adjunte controladores a 'submitHandler' y' invalidHandler'. – Ryley

0

Intente utilizar matrices de entrada:

<form action="try.php" method="post"> 
    <div id="events_wrapper"> 
     <div id="sub_events"> 
      <input type="text" name="firstname[]" />          
     </div> 
    </div> 
    <input type="button" id="add_another_event" name="add_another_event" value="Add Another" /> 
    <input type="submit" name="submit" value="submit" /> 
</form> 

y añade este guión y jQuery, usando foreach() para recuperar los datos de ello es $ _POST'ed:

<script>                      
    $(document).ready(function(){ 
     $("#add_another_event").click(function(){ 
     var $address = $('#sub_events'); 
     var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original 
     var newNum = num + 1; 
     var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress'); 

     //set all div id's and the input id's 
     newElem.children('div').each (function (i) { 
      this.id = 'input' + (newNum*5 + i); 
     }); 

     newElem.find('input').each (function() { 
      this.id = this.id + newNum; 
      this.name = this.name + newNum; 
     }); 

     if (num > 0) { 
      $('.clonedAddress:last').after(newElem); 
     } else { 
      $address.after(newElem); 
     } 

     $('#btnDel').removeAttr('disabled'); 
     }); 

     $("#remove").click(function(){ 

     }); 

    }); 
</script> 
3

El Mahesh publicado no es funciona porque el nombre del atributo falta:

Así que en lugar de

<input id="list" class="required" /> 

Se puede utilizar: la validación de formularios

<input id="list" name="list" class="required" /> 

Modified version

26

reinicio después de añadir nuevos campos.

function resetFormValidator(formId) { 
    $(formId).removeData('validator'); 
    $(formId).removeData('unobtrusiveValidation'); 
    $.validator.unobtrusive.parse(formId); 
} 
+3

Esta solución es mucho mejor –

+0

desde donde se necesita llamar a esta función? en el envío del formulario, o el método javascript que agrega un nuevo campo? –

+3

cuando estoy usando esto obtengo este error: 'UnEught TypeError: No se puede leer la propiedad 'parse' de undefined' –

1

Usted necesidad de volver a analizar la forma después de añadir contenido dinámico a fin de validar el contenido

$('form').data('validator', null); 
$.validator.unobtrusive.parse($('form')); 
1

En lo que respecta a la respuesta @RitchieD, aquí es una versión de jQuery plugin para facilitar las cosas si estás usando jQuery.

(function ($) { 

    $.fn.initValidation = function() { 

     $(this).removeData("validator"); 
     $(this).removeData("unobtrusiveValidation"); 
     $.validator.unobtrusive.parse(this); 

     return this; 
    }; 

}(jQuery)); 

Esto puede ser usado como esto:.

$("#SomeForm").initValidation(); 
Cuestiones relacionadas