2012-01-20 43 views
0

我發現很好的JavaScript在這裏javascript duplicate field如何限制重複表單字段的Javascript?

但問題是我想限制功能只能複製到10行。

在這裏我的代碼。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
<script type="text/javascript"> 

    (function($){ 
      $countForms = 1; 
      $.fn.addForms = function(){ 
         var myform = "<table>"+ 
         " <tr>"+ 
         "  <td>Field A ("+$countForms+"):</td>"+ 
         "  <td><input type='text' name='fielda["+$countForms+"]'></td>"+ 
         "  <td>Field B ("+$countForms+"):</td>"+ 
         "  <td><textarea name='fieldb["+$countForms+"]'></textarea></td>"+ 
         "  <td><button>remove</button></td>"+ 
         " </tr>"+ 
         "</table>"; 

         myform = $("<div>"+myform+"</div>"); 
         $("button", $(myform)).click(function(){ $(this).parent().parent().remove(); }); 

         $(this).append(myform); 
         $countForms++; 
      }; 
    })(jQuery);   

    $(function(){ 
     $("#mybutton").bind("click", function(){ 
       $("#container").addForms(); 
     }); 
    }); 

</script> 
</head> 
<body> 
<button id="mybutton">add form</button> 
<div id="container"></div> 

所以任何建議將不勝感激!

謝謝。

+0

您可以設置一些最大複製值一樣maxDuplicateCount = 10,然後對證同時呼籲addForms()。 。不會幫助..? –

+0

對不起,我真的是新手..你可以展示我應該把代碼放在哪裏? – ruslyrossi

+0

查看@ mrtsherman的答案張貼在下面,多數民衆贊成我的意思是 –

回答

2

呃,我覺得這個建議很髒。您的鏈接問題中有很多其他更好的答案。

$.fn.addForms = function(){ 
     if ($countForms == 10) { 
      $("#mybutton").unbind("click"); 
      return; 
     } 
     var myform = "<table>"+ 
+0

哦,但該代碼是正確的...謝謝.. :) – ruslyrossi

0

只需添加一個檢查到功能,迫使其停止在10場

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script> 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
<script type="text/javascript"> 
    (function($){ 
    $countForms = 1; 
    $formLimit = 10; 
    $.fn.addForms = function(){ 
     if(countForms >= formLimt){ 
     return; 
     } 
     var myform = "<table>"+ 
        " <tr>"+ 
        " <td>Field A ("+$countForms+"):</td>"+ 
        " <td><input type='text' name='fielda["+$countForms+"]'></td>"+ 
        " <td>Field B ("+$countForms+"):</td>"+ 
        " <td><textarea name='fieldb["+$countForms+"]'></textarea></td>"+ 
        " <td><button>remove</button></td>"+ 
        " </tr>"+ 
        "</table>"; 

     myform = $("<div>"+myform+"</div>"); 
     $("button", $(myform)).click(function(){ $(this).parent().parent().remove(); }); 

     $(this).append(myform); 
     $countForms++; 
    }; 
    })(jQuery);   

    $(function(){ 
    $("#mybutton").bind("click", function(){ 
     $("#container").addForms(); 
    }); 
    }); 
    </script> 
</head> 
相關問題