2013-08-27 33 views
0

我有一個表單要求用戶給設備類型一個名稱,並說出他們想分配給該設備類型的屬性數量。該表單調用下面的php文件,它使用循環來創建所需數量的屬性。從用戶輸入添加HTML表單域

我已經使用了name =「attribute」。$ i爲了能夠識別下一個php頁面上的每個屬性以將信息發送到數據庫。

<?php echo $_POST['device-name']; ?> 

    <?php 

     $num=$_POST['number-of-attributes']; 
     $num=intval($num); 

     for($i=0; $i<$num; $i++) { 

      newAttribute($i); 

     } 

     function newAttribute($i) { 

      echo ("<div id=\"new-attribute\">"); 
      echo ("<h3>New Attribute</h3>"); 
      echo ("<label for=\"attribute".$i."\">Name</label>"); 
      echo ("<input id=\"attribute\" type=\"text\" name=\"attribute".$i."\">"); 
      echo ("</div>"); 

     } 

    ?> 

但是我也希望用戶能夠點擊,例如:

<div id="small-button">New Attribute</div> 

,並創建另一組字段定義的屬性。

我該怎麼做?

在此先感謝

+2

您將使用JavaScript將元素插入到DOM中。你知道任何JavaScript嗎? –

+0

如何將輸入元素插入到JavaScript中的DOM中,併爲每個人賦予一個遞增值以在下一個php頁面上標識它們以將它們發送到數據庫? – mickzer

回答

0

使用Javascript/jQuery的:

var template = "<div class=\"new-attribute\">" 
      + "<h3>New Attribute</h3>" 
      + "<label for=\"attribute\">Name</label>" 
      + "<input id=\"attribute\" type=\"text\" name=\"attribute\">" 
      + "</div>"; 

$(document).ready(function() { 
// The DOM has loaded 
    $("#small-button").on('click', function() { 
    // The user clicked your 'New Attribute' button 
     // Append a new attribute to the <body> with `template` we defined above: 
     $(body).append(template); 
    }); 
}); 

注:我改變id="new-attribute"class="new-attribute"自會有大於1.

0

您需要爲上述工作使用JavaScript。在你的HTML文檔,在body element的結尾處添加以下script element:在客戶端

<script type="text/javascript"> 

var numberOfAttributes = 1; 

function newAttributeFields(e) { 
    // Creates the div 
    var div = document.createElement('div'); 
    div.id = 'new-attribute'; 

    // Appends the fields 
    div.innerHtml = '<h3>New attribute</h3><label for="attribute' + numberOfAttributes + '">Name</label><input id="attribute" type="text" name="attribute' + numberOfAttributes + '">'; 

    // Appends it to the body element 
    document.getElementsByTagName('body')[0].appendChild(div); 

    // Increments the number of attributes by one 
    numberOfAttributes = numberOfAttributes + 1; 
} 

var smallButton = document.getElementById('small-button'); 

// When the 'small button' is clicked, calls the newAttributeFields function 
smallButton.addEventListener('click', newAttributeFields, false); 

</script>