简体   繁体   English

将项目添加到表格-HTML / CSS / JS

[英]Add Item to Table - HTML/CSS/JS

Let's say I have a dropdown (or combobox) and it has list of things. 假设我有一个下拉列表(或组合框),并且其中包含内容列表。 Once I select one thing from the list, it will automatically add to Table. 从列表中选择一件事后,它将自动添加到表中。 How would I do that? 我该怎么做? Possible it is only HTML/JS? 可能只有HTML / JS吗?

Dropdown: 落下:

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

Table: 表:

<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>

Thanks. 谢谢。

Using jQuery: 使用jQuery:

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

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

});

I hope you get the idea. 希望您能明白。

Please try with the below code snippet. 请尝试使用以下代码段。

<!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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM