如何将数据推入值属性HTML,就像DataTables中每个选定行的数组一样?

时间:2018-10-29 06:14:38

标签: javascript jquery html

当我选择一行时,我正在使用DataTables创建一个测试项目。我希望每个选定的值都将使用jQuery附加到隐藏值属性(HTML)中。

row 1 value = 4
row 2 value = 5
row 3 value = 6

输出:

<input type="hidden" value=[4,5,6] />

1 个答案:

答案 0 :(得分:0)

尝试一下。

$(document).ready(function () {
    var table = $('#example').DataTable();

    $('#example tbody').on('click', 'tr', function () {
        $(this).toggleClass('selected');
    });

    $('#button').click(function () {
        var ids = $.map(table.rows('.selected').data(), function (item) {
            return item[0]
        });
        console.log(ids)
        $('#hidden_arr').val(JSON.stringify(ids));
        alert(table.rows('.selected').data().length + ' row(s) selected');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">btn</button>
<input type="text" value="" id="hidden_arr" />
<table id="example" class="display" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Id</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>


    <tbody>
        <tr>
            <td>1</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
        </tr>
         </table>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.5/js/jquery.dataTables.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.5/css/jquery.dataTables.css" rel="stylesheet"/>