2012-07-18 69 views
25

私はthis jquery validationプラグインを次のフォームに使用しました。動的に追加された入力フィールドを確認する

<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> 

追加ボタンをクリックすると、新しい入力が動的に追加されます。しかし、フォームが提出されると、最初の入力フィールドのみが検証されます。動的に追加された入力をどのように検証できますか? ありがとうございます...

+0

あなたは '$( 'フォーム')を試してみましたの( '提出'、機能(E){$(この).validate()。 ;返信false;}); ' – Krimo

+0

http://stackoverflow.com/a/26542591/5557983 @Stephen Mueckeによるこの解決策は私のために働いた –

答えて

26

入力には「名前」属性が必要です。ルールを動的に追加する必要があります.1つの選択肢は、フォームの送信時にルールを追加することです。

そして、ここでは、私がテストした私のソリューションであり、それは動作します:

<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> 

と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> 

幸運!それがあなたに合っているなら、答えを承認してください!

+2

あなたの努力のために大変ありがとう@Angel。それは魔法のように働いた。素晴らしい仕事:) – Rav

+2

あなたは大歓迎です! – Angel

+2

FWIWでは、document.readyで一度だけvalidateを呼び出してから、 'addInput'関数内でルールを追加することができます。検証の成功/失敗を示すには、ハンドラを 'submitHandler'と' invalidHandler'に追加してください。 – Ryley

0

は、入力配列を使用してみてください:

<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> 

と$ _POST'edされているデータを取得するためのforeach()を使用して、このスクリプトとjQueryを追加します。

<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

投稿1マヘシュではありません属性名がありません:

したがって、代わりに

<input id="list" class="required" /> 
あなたが使用することができます

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

Modified version

26

新しいフィールドを追加した後にフォームの検証をリセットします。

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

このソリューションは、この関数を呼び出す必要がある場所からはるかに良い –

+0

です。フォームの提出時に、または新しいフィールドを追加するjavascriptメソッド? –

+3

私はこのエラーが発生します: 'Uncaught TypeError:未定義のプロパティ 'parse'を読み取れません。 –

1

あなたは@RitchieD応答に関しては、コンテンツ

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

を検証するために動的コンテンツを追加した後、フォームを再解析する必要があり、ここでもし物事を容易にするために、jQueryプラグインのバージョンですあなたはjQueryを使用しています。

(function ($) { 

    $.fn.initValidation = function() { 

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

     return this; 
    }; 

}(jQuery)); 

これは、このように使用することができます:

$("#SomeForm").initValidation(); 
関連する問題