2011-01-06 112 views
0

我需要將某些輸入文本框的內容拖到數據庫中。顯示第一個盒子,但我使用這個JavaScript動態創建其中一些:將值添加到動態表單

var counter = 1; 
var limit = 10; 
function addInput(divName){ 
    if (counter !== limit) { 
      var newdiv = document.createElement('div'); 
      newdiv.innerHTML = " <input type='text' name='myInputs[]' size=40>"; 
      document.getElementById(divName).appendChild(newdiv); 
      counter++; 
    } 
} 

我怎麼能值添加到這將爲創建的,因此每個箱子是不同的形式,我可以在PHP中引用它們?

謝謝!

+0

不知道你想要什麼。你所有的輸入字段都可以通過$ _POST ['myInputs']`數組訪問。 – 2011-01-06 20:28:04

回答

0

編輯:從頭開始,我從來沒有嘗試過使用數組來分組輸入,但它的工作原理是這樣使用它。保持名稱的輸入,myInputs [],但參考在PHP這樣的:

你的第一場和

$_POST[myInputs][1] 

第二等。

+0

感謝您的快速回復,效果很好。我沿着相同的路線嘗試了一些東西,但我不熟悉Javascript語法。我將如何表示counter + 1,所以它會以2開頭? – Sebastian 2011-01-06 20:29:57

0
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>//use jQuery. it makes life easy. 
      <script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.4.2.js"%3E%3C/script%3E'))</script> 
      <script> 
       $(document).ready(function(){//fire when the page is ready 
        $('.addFields').click(function(){//any time someone clicks on a element with the class addFields 
         if($('.myInputs').length < 10){ // if there are less than 10 input fields... 
          $($(this).attr('rel')).append("<br/><input type='text' name='myInputs[]' class='myInputs' size='40' id='myInputs"+($('.myInputs').length)+"'>"); 
          // add another input field with an ID equal to it's place in line. 
           } 
        }); 
       }); 
      </script> 

     </head> 
     <body > 
      <a rel="#addToMe" class="addFields" href="#">Add a field</a><!-- the triggering element this can be anything that can be clicked on--> 
      <div id="addToMe"><!-- the element holding our input fields, new ones get added to the back of here, note that the trigger's rel attribute is the ID of this attribute and started with a "#' ID identifier--> 
       <input type='text' name='myInputs[]' class='myInputs' size='40' id='myInputs0'> 
      </div> 

     </body>