반응형
250x250
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Notice
Recent Posts
Today
Total
관리 메뉴

네이처리 노트

[jQuery] plugin | datatable 본문

개발기록/Javascript

[jQuery] plugin | datatable

네이처리 2022. 9. 7. 15:46
728x90
반응형

공부하면서 정리한 내용입니다
참고한 내용은 링크를 확인해주세요





원하는 스타일 프레임워크 및 확장기능을 선택하여 CDN 혹은 다운로드 할 수 있다.


테이블에서 Ajax 통신

https://datatables.net/reference/option/ajax

ajax

ajax Since: DataTables 1.10 Load data for the table's content from an Ajax source. Description DataTables can obtain the data that it is to display in the table body from a number of sources, including from an Ajax data source, using this initialisation pa

datatables.net

테이블 정렬순서 고정하기

https://datatables.net/reference/option/orderFixed

orderFixed

orderFixed Since: DataTables 1.10 Ordering to always be applied to the table. Description The option works in tandem with the order option which provides an initial ordering state for the table which can then be modified by the user clicking on column head

datatables.net




datatable 옵션으로 Checkbox 넣기

https://datatables.net/extensions/select/examples/initialisation/checkbox.html

DataTables example - Checkbox selection

Checkbox selection A selected row is typically shown in a DataTable by using a highlight background colour - however, it can also be useful to use other styling options to convey the selected state of items in a table to the end user. A common option is to

datatables.net



table row 추가하기

https://www.ksia.or.kr/plugin/DataTables-1.10.15/examples/api/add_row.html

DataTables example - Add rows

This example uses a little bit of additional CSS beyond what is loaded from the library files (below), in order to correctly display the table. The additional CSS used is shown below: The following CSS library files are loaded for use in this example to pr

www.ksia.or.kr


table row 확장하기

선택한 row 하단에 아코디언(익스펜더블) 형식으로 슬라이딩되서 펼쳐지거나 접혀지는 형태

https://datatables.net/blog/2014-10-02#CSS

Sliding child rows

Thursday 2nd October, 2014 Sliding child rows The ability to show information that relates to a specific record in a table can greatly simplify the primary display of a table for the end user, while still allowing access to arbitrarily complex data in the

datatables.net


테이블 드롭앤드랍

// 사용하기
$("table").tableDnD();

// 사용 멈추기
$("table tr").addClass("nodrag nodrop").css("cursor", "auto");

http://isocra.github.io/TableDnD/

TableDnD

jQuery plug-in to drag and drop rows in HTML tables

isocra.github.io


서버에서 전달받은 값 렌더링하기

예제 1

더보기
dTable.destroy(); // 한번 파괴해야 다시 테이블이 다시 그려진다.
dTable = $("#table").DataTable({
    autoWidth:   false,
    ordering: false,
    searching: false,
    paging: false,
    info: false,
    data: data, // 반복문으로 데이터 렌더링 후 추가가능
    columns: [  // 디폴트 데이터값
        { data: "table_key" },
        { data: "size" },
        {   
            data: "price",
            render : function(data, type, row){
								// 보여주고자 하는 모습으로 렌더링가능
                return `${data} 원`;
            }
        }
    ],
    pagingType: "numbers",
    language: {"emptyTable" : "데이터가 없는 경우, 테이블에 출력되는 텍스트를 작성하는 곳"},
    pageLength: 20,
	  columnDefs: [ 
        { 
            targets : [0, 1, 2], // column
            width: "60px",       
        }
    ]
});

예제2

더보기
<!--HTML-->

<table id="table" class="table"  >
    <thead style="font-size: 12px;">
	        <tr>
	            <th>정보</th>
	            <th>크기</th>
	            <th>가격</th>
	            <th> 펼쳐보기 </th>                            
	        </tr>
    </thead>
    <tbody style="background-color: #eee;">  </tbody>
    <!--데이터테이블로 채운다. 바디데이터는 헤드의 컬럼개수와 동일해야한다.-->
</table>
//jquery

dTable = $("#table").DataTable({
        destroy: true,
        autoWidth:   false,
        ordering: false,
        searching: false,
        paging: false,
        info: false,
        data: color_data,
        columns: [        // 디폴트 데이터값
            { 
                data: "table_key",
                render: function(data, type, row){
                    return `캔디번호${data}_${row.color}`;
                } 
            },
            { 
                data: "size",
                render: function(data, type, row){
                    switch(data){
                        case "small":
                            return "S";
                        case "medium":
                            return "M";
                        case "large":
                            return "L";
                    }
                }
            },
            { 
                data: "price",
                render : function(data, type, row){
                    return `${data} 원`;
                }
            },
            {
                className: 'details-control',
                orderable: false,
                data: null,
                defaultContent: '+'
            }
        ],
        pagingType: "numbers",
        language: {"emptyTable" : "색상을 선택해주세요"},
        pageLength: 20,
        columnDefs: [ 
            { 
                targets : [0, 1, 2, 3],
                width : "60px"
            }
        ]   
    });

예제3

더보기
let data = [];

    for (let i = 0; i < _adviceList.length; i++) 
    {
        let list = Array();

        let title = _adviceList[i]['title'];
        let md_account = _adviceList[i]['md_account'];
        let reg_date = _adviceList[i]['reg_date'];
        let start_date = Number(_adviceList[i]['start_date']);

        let visibleCustom;
        let today = Date.parse( new Date() );
       

        list.push(`<input type="checkbox" name="adviceChk" value=${i}>`);
        list.push(`<div name="viewOrder" value=${i}> ${i + 1} </div>`);
        list.push(title);
        list.push(md_account);
        list.push(reg_date);
        list.push(`<button type="button" id="modifyModalBtn" class="btn tableInnerBtn" onclick="adviceAddOrFixed(false, ${i})"> 수정 </button>`);

        data.push(list);
    }

    _table.destroy();
    _table = $('#table').DataTable(
        {
            data: data,
            deferRender: false,
            autoWidth: false,
            ordering: false,
            searching: false,
            paging: false,
            info: false,
            pagingType: "numbers",
            pageLength: 20,
            columnDefs: [
                {className: 'text-left', targets: [2]},
            ]
        });


예제4

더보기
_table.destroy();
_table = $('#table').DataTable( 
{
    data:        data,
    deferRender: false,
    autoWidth:   false,
    ordering: false,
    searching: true,
    paging: true,
    pagingType: "numbers",
    aLengthMenu: [[20, 50, 100, 200], ["20개", "50개", "100개", "200개"]],
    language: { "lengthMenu" : "_MENU_","search" : "", "emptyTable" : "데이터가 없습니다"},
    columnDefs: [
      { className: 'text-left', targets: [3] },
    ],
    dom: "<'f mb-10' <'f'<'b1'><'w'lf>> <'b2'>>"
        + "<'mb-25't>"
        + "<'pagination justify-content-center'p>"
});
  
$("div.b1").html(` <button type="button" id="order" class="btn orderBtn" onclick="orderButton()"> 순서 </button>`);
$("div.b2").html(` <button type="button" id="del" class="btn deleteBtn noTouchBtn" onclick="delButton(-1)"> 삭제 </button>`);





728x90
반응형
Comments