2010-08-18 40 views
0

我有一個表單,其中包含一個名爲「Product」的塊,其中包含文本輸入。在該塊內部,用戶可以按下「添加項目」並讓JS再顯示一個字段。直到現在一切正常。用於顯示額外表單域的JavaScript

我試着添加一個函數來添加一個新的「產品」塊,但沒有運氣。你有什麼提示嗎?

Product 
Item: <input> Price: <input> 
Item: <input> Price: <input> 
       <a>add item</a> <- this works 

<a>add Product</a>    <- this is the part that I can't figure out :(

任何幫助將不勝感激。

謝謝!

更新: 這裏是JS的項目和價格領域:

<script type="text/javascript"> 
    $(document).ready(function(){ 
    var counter = 2; 
    $("b.add-item").click(function() { 
    if(counter>5){ alert("Max 6 items allowed"); return false; } 
    var newTextBoxDiv = $(document.createElement('div')) 
     .attr("id", 'TextBoxDiv' + counter); 
    newTextBoxDiv.after().html(
      '<span class="item">' + 
      '<label>Item:</label>'+ 
      '<input type="text" name="item1[]" id="textbox' + counter + '" value="" >' + 
      '<label>&nbsp;&nbsp;&nbsp;Price:</label>'+ 
      '<input type="text" name="price1[]" id="textbox' + counter + '" value="" >' +  
      '</span>' 
      ); 
    newTextBoxDiv.appendTo(".items"); 
    counter++; 
    }); 
    $("b.remove-item").click(function() { 
    if(counter==1){alert("No more textbox to remove"); 
    return false; }  counter--; 
    $("#TextBoxDiv" + counter).remove();}); 
    $("#getButtonValue").click(function() { var msg = ''; for(i=1; i<counter; i++){ msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val(); }alert(msg); }); 
    }); 
</script> 
+1

告訴我們您的JS – 2010-08-18 13:30:20

回答

0

也許做一個表,並添加新行?

HTML:

<table id="myTable"> 
    <tr> 
    <th>Item</th> 
    <td><input /></td> 
    <th>Price</th> 
    <td><input /></td> 
    </tr> 
    <tr> 
    <th>Item</th> 
    <td><input /></td> 
    <th>Price</th> 
    <td><input /></td> 
    </tr> 
</table> 
<a onclick="add_row(); return false;">Add Product</a> 

的JavaScript:

function add_row() 
{ 
    var table = document.getElementById('myTable'); 
    if(!table) return; 
    // Table row 
    var row = document.createElement('row'); 
    table.appendChild(row); 
    // "Item:" 
    var th1 = document.createElement('th'); 
    th1.innerText = 'Item:' 
    row.appendChild(th1); 
    // Item input 
    var td1 = document.createElement('td'); 
    row.appendChild(td1); 
    var input1 = document.createElement('input'); 
    td1.appendChild(input1); 
    // "Price:" 
    var th2 = document.createElement('th'); 
    th2.innerText = 'Price:' 
    row.appendChild(th2); 
    // Price input 
    var td2 = document.createElement('td'); 
    row.appendChild(td2); 
    var input2 = document.createElement('input'); 
    td1.appendChild(input2); 
} 

我認爲這應該工作...

+0

哎呦,我想我誤解了問題:好吧,你可能可以用這個方法解決這個問題...... – Frxstrem 2010-08-18 13:42:05

+1

請將* ple ase *不要像這樣寫HTML - '表格的格式不好。正確的標記應該與列表。 '輸入**必須**具有'type'屬性,並且儘可能避免內聯事件。 – 2010-08-18 13:49:52