Could you point the correct place to embed a Datatables Bootstrap plugin  on this existing code to have column filter feature?

Eduardo Fuerte
Eduardo Fuerte used Ask the Experts™
on
Hi Experts

Could you point the correct place to embed a Datatables Bootstrap plugin  on this existing code to have column filter feature?

I need to put a filter in an existing "Datatables"  Bootstrap plugin, acordingly to that:

img003o

Datatables site suggest to put this code to complete this task

$(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );
 
    // DataTable
    var table = $('#example').DataTable();
 
    // Apply the search
    table.columns().every( function () {
        var that = this;
 
        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );

Open in new window


My problem is how to embed this in this existing code:
	
		function datatables($fields, $options, $search) {

			$order = $cont = 0;
			$order_type = "asc";
			
			if(isset($options['order'])) {
			
				if(isset($options['order_type']) && $options['order_type'] == 'desc')
					$order_type = 'desc';
				
				foreach($fields as $field => $label) {
					
					if($options['order'] == $field) {
						$order = $cont;
					}

					$cont++;
				}


			}

			$datatables = '
				<link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.bootstrap.css">
				<link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.plugins.css">

				<script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/jquery.dataTables.js"></script>
				<script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/dataTables.bootstrap.js"></script>
				';

			if (!isset($options['id']))
				$options['id'] = 'datatables_ajax';

			if (!isset($options['search_submit']))
				$options['search_submit'] = '.search_submit';

			$datatables .= '

			<script type="text/javascript">

				$(document).ready(function(){

					$("#pesquisar_groups_form").on("submit",function(){

						// não submete pagina - dont reload
						return false;

					});
					
					$(".clear_pesquisa").on("click",function(){

						// $("#pesquisar_groups_form").trigger("reset");
						redrawDataTables("");
					});

					redrawDataTables("");

					$("'.$options['search_submit'].'").on("click", function (e) {

						var table = "";
						var where = {';

							if (isset($search['like'])) {

								$datatables .= '"like" : {';

								$cont = 0;
								foreach($search['like'] as $val) {

									if($cont == 0)
										$datatables .= '"'.$val.'" : $("#pesquisar_groups_form").find("#'.$val.'").val()';
									else
										$datatables .= ',"'.$val.'" : $("#pesquisar_groups_form").find("#'.$val.'").val()';

									$cont++;

								}
								$datatables .= '}';

								if (isset($search['where']))
									$datatables .= ',';

							}

							if (isset($search['where'])) {

								$datatables .= '"where" : {
									';

								$cont = 0;
								foreach($search['where'] as $val) {

									if($cont == 0)
										$datatables .= '"'.$val.'" : $("#pesquisar_groups_form").find("#'.$val.'").val()
									';
									else
										$datatables .= ',"'.$val.'" : $("#pesquisar_groups_form").find("#'.$val.'").val()
									';

									$cont++;

								}
								$datatables .= '}
								';
							}

						$datatables .= '}
						';
						
						$datatables .= '

						redrawDataTables(where);
					});
				});

				function redrawDataTables(where) {



					if (typeof table != "undefined" && typeof table != undefined && table != "") {

						$("#exemplo").empty();
						table.destroy();
					}

					if (typeof where == "undefined" || typeof where == undefined) {
						where = "";
					}

					table =  $("#' . $options['id'] . '").DataTable({
						"paging":   true,
						// "pagingType": "scrolling",
						"pagingType": "full_numbers",
						// "sPaginationType": "four_button",
						"retrieve": true,
						"searching": false,
						"ordering": true,

						"order": [
							[ 
								'.$order.', "'.$order_type.'"
							]
						],

						aaSorting: [],

						"lengthChange": false,
						"info": false,
						"ajax": {
							"url": "' . base_url() . $options['controller'] . '/' . $options['action'].'",
							"type": "post",
							"data": where,
							"processing": true,
						},
						"language": {
							"sEmptyTable": "Nenhum registro encontrado",
							"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
							"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
							"sInfoFiltered": "(Filtrados de _MAX_ registros)",
							"sInfoPostFix": "",
							"sInfoThousands": ".",
							"sLengthMenu": "_MENU_ resultados por página",
							"sLoadingRecords": "Carregando...",
							"sProcessing": "Processando...",
							"sZeroRecords": "Nenhum registro encontrado",
							"sSearch": "Pesquisar",
							"oPaginate": {
								"sNext": "",
								"sPrevious": "",
								"sFirst": "",
								"sLast": ""
							},
							"oAria": {
								"sSortAscending": ": Ordenar colunas de forma ascendente",
								"sSortDescending": ": Ordenar colunas de forma descendente"
							}
						}
					});

					$("#datatables tr").addClass("tr_clicked meeta-cursor-pointer");
				}
			</script>';

			 $datatables .= '

				<style>
					.pagination > li:last-child > a{
						z-index: 0;
					}
					.input-group {
						z-index: 0;
					}
				</style>';

				$datatables .= '

				<table id="' . $options['id'] . '" class="table admin-form theme-warning fs13" cellspacing="0" width="' . $options['width'] . '">
					<thead>
						<tr>';

					if(array_key_exists('active_ind',$fields))
						$fields = array_merge($fields, array('acoes'=>'Ações'));

					foreach ($fields as $field => $title) {
						$datatables .= '<th>' . $title . '</th>';
					}

				$datatables .=
						  '</tr>
						</thead>
					</table>';

			return $datatables;
		}

Open in new window


Thanks in advance!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi,
which datatable version are you using as old and new version are completely different syntax
check the version in datatable.js file.

I'm using  datatble  a lot and their filter function is not very flexible
with template

Are you using server side or client side filtering?

You may like to check this datatable plugin yadcf
https://github.com/vedmack/yadcf
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Sorry


I just omit the {  } in the jquery else. That's the problem.
 if (serv != 'Sim')
            {
                $(".custo").hide();
                $("#divReembolso").hide();
            }         
            else
            {
                $(".custo").show();
                $("#divReembolso").show();
            }

Open in new window


It runs that way
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi lenamtl

Sorry again, I misconcept the questions!

I'm going to check your reply carefully.
Success in ‘20 With a Profitable Pricing Strategy

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi

My problem here is where to put the code suggested in Datatables plugin site inside my existing code.
Which datatable.js version are you using?

Based on their example found at
https://datatables.net/examples/api/multi_filter.html
You need to use the provided code for each part js, html, CSS

Don't forget the CSS part
tfoot input {
        width: 100%;
        padding: 3px;
        box-sizing: border-box;
    }

Open in new window


this js part is can be replaced by your datatable code
 // DataTable
    var table = $('#example').DataTable();

Open in new window


You can tried with this basic example to test it, then apply to your code.
This should work and your code seems ok too, but it's hard to say without seen the page...

Check with Chrome dev tool if there is any error (rigth click Inspect).
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi

I'm not sure what is the correct version, based on:
img003
You are looking in the wrong directory
you checked in the extension directory
instead you need to check in datatable directory
vendor/plugins/datatables
and find datatable.js
Eduardo FuerteDeveloper and Analyst

Author

Commented:
I couldn't find datatable.js at the folder you pointed:

img001
this may depends of the template you are using

in my case i'm using these latest datatables  with Bootstrap  & responsive
js/plugins/datatables/media/
<script src="js/plugins/datatables/media/js/jquery.dataTables.min.js"></script>
<script src="js/plugins/datatables/media/js/dataTables.bootstrap.min.js"></script>

js/plugins/datatables/extensions/
<script src="js/plugins/datatables/extensions/Responsive/js/dataTables.responsive.min.js"></script>
<script src="js/plugins/datatables/extensions/Responsive/js/responsive.bootstrap.min.js"></script>
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Hi

Here it is

img003
Eduardo FuerteDeveloper and Analyst

Author

Commented:
We are using:

$datatables = '
            <link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.bootstrap.css">
            <link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.plugins.css">

            <script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/jquery.dataTables.js"></script>
            <script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/dataTables.bootstrap.js"></script>
            ';

Open in new window


Something changes?
Can you create a codepen so we can see the problem?

Here is another way to do it
https://codepen.io/sfauch1/pen/YGWGyN
Eduardo FuerteDeveloper and Analyst

Author

Commented:
Thanks lenamtl

I'm going to follow the steps you pointed.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial