jquery

dataables search & customize 하기

그래그래그래놀라 2020. 8. 4. 15:37

/////////////  html

<div  id="search_from" class="text-right">
        <select name="select_filter" id="select_filter">
        <option value="0">#</option>
        <option value="1">Country</option>
        <option value="3">Type</option>
        <option value="4">Title</option>
        <option value="5">Active</option>
        <option value="6">Sorting</option>
        <option value="7">Start At</option>
        <option value="8">Finish At</option>
    </select>


    <input type="text" name="search_filter" id="search_filter">
</div>

<table id="dataTables">

  ...생략

</table>



//////////  jquery
let
$table = $("#dataTables").DataTable({
    ordering: true,
    order: [[0, "desc"]],
    lengthChange: false,
    pageLength: 50,
});

 

$('.dataTables_filter').remove()// dataTable 자체 search input 없애기

$('#select_filter').change(function () { // select 선택값에 따라  해당 선택 열 input이 검색하는곳 변경
    $table.columns('').search('').draw();
    $table.columns(Number($('#select_filter').val())).search($('#search_filter').val()).draw();
});

$('#search_filter').keyup(function () { //input의 값대로 search
    let $value = $(this).val();
    $table.columns(Number($('#select_filter').val())).search($value).draw();
})

 

//////////////2번쨰 방법

dataTablesd의 search도 가져와서 이중검색하기

 

$table = $("#dataTables").DataTable({
    ordering: false,
    "language": {
    "search": "Filter (Title):"  /// <<이부분 추가
},
    dom: "<'row'<'col-sm-12 col-md-6'l><'#select_input.col-sm-12 .col-md-6'f>>" +
             "<'row'<'col-sm-12'tr>>" +
             "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
    lengthChange: false,
    pageLength: 50,
    columnDefs: [
            {targets: [0, 1, 2, 3, 5, 6]}//검색되는부분
    ]
})


//html 부분에서  #search_from 부분을 전부 삭제하고 직접 append하기 

var html_select = "<div class=\"text-right\" style=\"float:right; margin-right:8px;\">\n" +
    " <select name=\"select_filter\" id=\"select_filter\">\n" +
    " <option value=\"2\">Country</option>\n" +
    " </select>\n" +
    " <input type=\"text\" name=\"search_filter\" id=\"search_filter\" class=\"form-control input-inline input-sm\">\n" +
    " </div>";

$('#select_input').append(html_select);

$('#select_filter').change(function () {
    $table.columns('').search('').draw();
    $table.columns(Number($('#select_filter').val())).search($('#search_filter').val()).draw();
});

$('#search_filter').keyup(function () {
    let $value = $(this).val();
    $table.columns(Number($('#select_filter').val())).search($value).draw();
});