2014-07-26 28 views
1

比方說,我有一個下拉列表(或組合框),它有一些事情的列表。一旦我從列表中選擇了一件事物,它就會自動添加到表格中。我會怎麼做?可能它只是HTML/JS?添加項到表 - HTML/CSS/JS

下拉:

<select class="combobox form-control" style="display: none;"> 
    <option value="" selected="selected">Point Guard</option> 
    <option value="CP3">Chris Paul (93)</option> 
</select> 

表:

<table class="table"> 
    <thead> 
     <tr> 
     <th>Position</th> 
     <th>First Name</th> 
     <th>Last Name</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
     <td>1</td> 
     <td>Mark</td> 
     <td>Otto</td> 
     </tr> 
     <tr> 
     <td>2</td> 
     <td>Jacob</td> 
     <td>Thornton</td> 
     </tr> 
     <tr> 
     <td>3</td> 
     <td>Larry</td> 
     <td>the Bird</td> 
     </tr> 
    </tbody> 
</table> 

感謝。

+0

您能否詳細說明您的情況? –

+0

@JayeshGoyani一旦我從下拉菜單中選擇了該項目,該項目將被插入到表格中。你懂了?我將如何插入我選擇的項目,添加到表格中。 –

+0

使用'.onchange'事件,然後創建一些HTML並將其附加到您的表中。 – tymeJV

回答

0

使用jQuery:

$('.combobox').change(function(e) { 

    var selectedVal = $(this).val(); 
    $('.table').append('<tr><td>' + selectedVal + '</td></tr>'); 

}); 

我希望你的想法。

+0

謝謝!有用!我有一個問題,如果我想更改項目,我將如何從表格中刪除項目? –

+0

@bensingh給予'tr'一個id而不是'.table'代碼。而不是使用'.append'來使用jQuery的'.html'功能。 –

+0

@bensingh明白了嗎? –

0

請嘗試使用下面的代碼片段。

<!DOCTYPE html> 
<html> 
<head> 
    <title>Test</title> 
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
    <script> 
     $(document).ready(function() { 
      $(".combobox").change(function() { 
       var temp1 = $(".combobox option:selected").text().split(' '); 
       $('.table tr:last').after('<tr><td>' + $('.table tr').length + '</td><td>' + temp1[0] + '</td><td>' + temp1[1] + '</td></tr>'); 
      }); 
     }); 

     function removeItem() { 
      $('.table tbody tr:first').remove(); 
      //.eq() -- You can also use this to fetch nth row 
     } 
    </script> 
</head> 
<body> 
    <select class="combobox form-control"> 
     <option value="" selected="selected">Point Guard</option> 
     <option value="CP3">Chris Paul (93)</option> 
    </select> 
    <button onclick="removeItem()">Remove First Row</button> 
    <table class="table"> 
     <thead> 
      <tr> 
       <th>Position</th> 
       <th>First Name</th> 
       <th>Last Name</th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr> 
       <td>1</td> 
       <td>Mark</td> 
       <td>Otto</td> 
      </tr> 
      <tr> 
       <td>2</td> 
       <td>Jacob</td> 
       <td>Thornton</td> 
      </tr> 
      <tr> 
       <td>3</td> 
       <td>Larry</td> 
       <td>the Bird</td> 
      </tr> 
     </tbody> 
    </table> 


</body> 
</html>