チェックボックスで列をフィルタリングできるデータテーブルがあります。チェックボックスをオンにすると列が表示され、オフにすると列が非表示になります。ページの更新時にチェックボックスの状態 (つまり、チェックされているかどうか) を保存しようとしていますが、これは機能します (つまり、チェックされたボックスは更新時にまだチェックされていますが、チェックされていないボックスはチェックされていません)。残念ながら、これは列が表示されるかどうかに影響を与えないようです。したがって、チェックボックスをクリックすると列が表示され、もう一度クリックすると (チェックを外すと) 列は表示されなくなります。更新時にチェックボックスの状態は同じですが、列は影響を受けなくなりました。チェックボックスのステータスを保存する方法だけでなく、ページの更新時にそれらのチェックボックスが持つ効果 (列を表示するかどうか) を保存する方法も理解しようとしています。
チェックボックスは次のようになります (データテーブルのデフォルトの動作を表示するために、チェックボックスにチェックを追加したことに注意してください)。
<label for="address" class="label">Name
<input class="box" type="checkbox" name="pname" id="pname" onclick="fnShowHide(0);" checked>
</label>
<label for="address" class="label">Address
<input class="box" type="checkbox" name="address" id="address" onclick="fnShowHide(1);" checked>
</label>
<label for="address" class="label">City
<input class="box" type="checkbox" name="city" id="city" onclick="fnShowHide(2);" checked>
</label>
<label for="address" class="label">State
<input class="box" type="checkbox" name="state" id="state" onclick="fnShowHide(3);" checked>
</label>
<label for="address" class="label">DOB
<input class="box" type="checkbox" name="dob" id="dob" onclick="fnShowHide(4);" checked>
</label>
<label for="address" class="label">Occupation
<input class="box" type="checkbox" name="occupation" id="occupation" onclick="fnShowHide(5);">
</label>
<label for="address" class="label">Vehicle Type
<input class="box" type="checkbox" name="vehicle_type" id="vehicle_type" onclick="fnShowHide(6);" checked>
</label>
データテーブルは次のようになります (ShowHide 関数を使用):
var table = $('#people');
table.dataTable({
"iDisplayLength": 500,
"bPaginate": false,
"aLengthMenu": [[-1, 25, 50, 100], ["All", 25, 50, 100]],
'aoColumns': [
/* Name */ null,
/* Address */ null,
/* City */ null,
/* State */ null,
/* DOB */ { "bSortable": false },
/* Occupation */ { "bVisible": false },
/* Vehicle Type */ { "bVisible": false }
],
'sPaginationType': 'full_numbers',
'sDom': '<"dataTables_header"lfr>t<"dataTables_footer"ip>',
'fnInitComplete': function( oSettings )
{
table.closest('.dataTables_wrapper').find('.dataTables_length select').addClass('select blue-gradient glossy').styleSelect();
tableStyled = true;
}
});
function fnShowHide( iCol )
{
/* Get the DataTables object again - this is not a recreation, just a get of the object */
var oTable = $('#people').dataTable();
var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
oTable.fnSetColumnVis( iCol, bVis ? false : true );
}
チェックボックスの状態を維持するために使用している関数は次のとおりです。
$("input.box").each(function() {
var mycookie = $.cookie($(this).attr('name'));
if (mycookie && mycookie == "true") {
$(this).prop('checked', mycookie);
}
});
$("input.box").change(function() {
$.cookie($(this).attr("name"), $(this).prop('checked'), {
path: '/',
expires: 365
});
});