datatables default regex to search only start - javascript

Hi have the java script for datatables as below, How can define it so that the search is done only for start values, eg : [ hello, hello_all, all_hello] is there and my search key word is "hel" i should get filter of [hello,hello_all].
$('#example').DataTable( {
data: new_data,
dom: '<"top"fB>rt<"bottom"ipl>',
buttons:['csv'],
search :{"bSmart": false,
"regex":true},
columns: [
{ title: "Action" },
{ title: "Input" },
{ title: "State" },
{ title: "Completed" },
{ title: "Project" },
],
"order": [[ 3, "desc" ]]
});

See the documentation:
https://datatables.net/examples/api/regex.html
The filterColumn function is what you looking for I think.
I hope that helps.
Gruesse
function filterGlobal () {
$('#example').DataTable().search(
$('#global_filter').val(),
$('#global_regex').prop('checked'),
$('#global_smart').prop('checked')
).draw();
}
function filterColumn ( i ) {
$('#example').DataTable().column( i ).search(
$('#col'+i+'_filter').val(),
$('#col'+i+'_regex').prop('checked'),
$('#col'+i+'_smart').prop('checked')
).draw();
}
$(document).ready(function() {
$('#example').DataTable();
$('input.global_filter').on( 'keyup click', function () {
filterGlobal();
} );
$('input.column_filter').on( 'keyup click', function () {
filterColumn( $(this).parents('tr').attr('data-column') );
} );
} );

I have a separate search field for one of the columns and here's my solution for begins-with search:
vm.searchForLocation = function() {
vm.dtInstance.DataTable.column(2)
.search("^"+vm.locationCode, true, false )
.draw();
}

Related

Isnull function and how to display the correct set of data through javascript to a html table

I have this set of javascript script on datatable:
<script>
$(document).ready(function() {
var table = $('#elogbooktable').DataTable( {
"ajax": {url: "testing_getdetaildata.php", dataSrc: ""},
'columnDefs': [ {
'targets': 3,
'createdCell': function(td, cellData, rowData, row, col) {
if(rowData[4]) {
$(td).html(rowData[4]);
}
}
} ],
'filterDropDown': {
columns: [
{
idx: 5
}
],
bootstrap: true
},
rowCallback: function(row, data, index){
if(new Date(data[42]) < Date.now()){
$(row).find('td:eq(42)').css('background-color', '#f8d7da');
}
},
})
<?php $i=13;
foreach($columns as $id=>$value) {
print "showHideColumn($id, $i);\n";
$i++;
}
?>
//Add a text search box to each footer cell
table.columns().every( function () {
$(this.footer()).html("<input type='text' style='width:100%;' placeholder='Search'/>");
});
//Full table search functionality
// Column search function
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that.search( this.value, true ).draw();
}
});
});
var buttons = new $.fn.dataTable.Buttons(table, {
'buttons': ['pageLength','copyHtml5',
{
extend: 'excelHtml5',
},
{
extend: 'print',
}]
}).container().appendTo($('#envdetail_wrapper .col-sm-6:eq(0)'));
setInterval( function () {
table.ajax.reload();
}, 300000 );
});
function showHideColumn(id, number) {
var dtable = $('#elogbooktable').DataTable();
if(dtable.column(number).visible() === true) {
if($(id).attr("class").includes("btn-primary")) {
$(id).removeClass("btn-primary");
$(id).addClass("btn-default");
}
dtable.column(number).visible(false);
}
else {
if($(id).attr("class").includes("btn-default")) {
$(id).removeClass("btn-default");
$(id).addClass("btn-primary");
}
dtable.column(number).visible(true);
}
}
</script>
The MySQL query is like this from testing_getdetaildata.php:
select *, ifnull(Board_ID,'') as Board_ID1 from Lab_WIP_History a LEFT join chamber_data b ON
a.LOT_LOCATION = b.Testtag LEFT JOIN chamber_data_1 c
ON a.LOTID = c.lotid;
And the query table is like this:
LOT_LOCATION, Zone, LOT_ID, DESIGN_ID, BOARD_ID, BOARD_ID1
SGBAKE.0012, '', CVN4BL2.11, NM112, NULL, ''
In the webpage, esp for
'targets': 3,
'createdCell': function(td, cellData, rowData, row, col) {
if(rowData[4]) {
$(td).html(rowData[4])
, the printed result in the webpage is like this:
LOT_LOCATION, Zone, LOT_ID, BOARD_ID
SGBAKE.0012, '', CVN4BL2.11, NM112
Which is not what i want since I want the Board_ID value in the table displayed to be replaced by BOARD_ID1. So, what I want is like this:
LOT_LOCATION, Zone, LOT_ID, BOARD_ID
SGBAKE.0012, '', CVN4BL2.11, ''
Does anyone know how to solve this table display issue? Any help is appreciated thank you!

datatables buttons enable/disable example not working

I'm using datatables with custom buttons. I'm looking in the examples, also googled a bit but I didn't find a working solution.
The problem is that, when I deselect the row the button is still enabled. What is the proper way to enable/disable the buttons when a row is selected/deselected?
var table = $('#example').DataTable( {
serverSide: true,
dom: 'Bfrtip',
ajax: '/get?op=2',
columns: [
{ data: 'id' },
// more columns
],
buttons: [
{
text: 'New',
action: function ( e, dt, node, config ) {
window.location.href = '/property?option=new'
}
},
{
text: 'Modify',
action: function ( e, dt, node, config ) {
window.location.href = '/property?option=modify&id=' + data.id
},
enabled: false
},
{
text: 'Delete',
action: function ( e, dt, node, config ) {
},
enabled: false
}
],
select: true
} );
table.on( 'select', function () {
var selectedRows = table.rows( { selected: true } ).count();
table.button( 1 ).enable( selectedRows === 1 );
table.button( 2 ).enable( selectedRows === 1 );
table.button( 3 ).enable( selectedRows === 1 );
//table.button( 1 ).enable( selectedRows > 0 );
} );
Also how can I get the id value for the selected row?
action: function ( e, dt, node, config ) {
window.location.href = '/property?option=modify&id=' + data.id
},
You need to add an event handler for the deselect. see https://datatables.net/reference/event/deselect
It should be something like below...
table.on( 'deselect', function () {
table.button( 1 ).disable();
table.button( 2 ).disable();
table.button( 3 ).disable();
} );
As for getting a row id an example can be found here
I think you are a bit confused over the .id() function you are using. It does not return value of you data field called id. It returns the tr attribute of id. If you do not set it, it will return undefined.
if you return DT_RowId as part of your dataset, it will be added automatically. {id:5, DT_RowId:"5"}. Or, client side, use the JQuery map function to add the field before you use it. Because using a straight integer as an id, it could get you in trouble if it gets duplicated in another table or element so I ususally do something like this...
var mydata = [{"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
}];
Using the extn id, I map to the dt_rowid...
$.map(mydata, function (item, key) {
item["DT_RowId"] = item["extn"]});
then use that data in my table...
$(document).ready(function() {
$('#example').DataTable( {
data:mydata,
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );

How to set selected to option using ddSlick after postback?

I need to use image drop-down list from http://designwithpc.com/plugins/ddslick I am trying to set "selected" option after postback, but I get infinite loop of postbacks. Here is my code:
<form id="form1">
<select id="localeId" name="localeId"></select>
</form>
<script type="text/javascript">
//Dropdown plugin data
var ddData = [
{
text: "English",
value: "en",
selected: false,
description: "English",
imageSrc: "/assets/img/flags-icons/en-flag.png"
},
{
text: "Portuguese",
value: "pt",
selected: false,
description: "Portuguese",
imageSrc: "/assets/img/flags-icons/pt-flag.png"
},
{
text: "Russian",
value: "ru",
selected: false,
description: "Russian",
imageSrc: "/assets/img/flags-icons/ru-flag.png"
},
{
text: "Spanish",
value: "es",
selected: false,
description: "Spanish",
imageSrc: "/assets/img/flags-icons/es-flag.png"
}
];
$('#localeId').ddslick({
data: ddData,
defaultSelectedIndex: 3,
onSelected: function (data) {
if (data.selectedIndex > 0) {
$('#hidCflag').val(data.selectedData.value);
$.cookie('lang', document.getElementById("hidCflag").value, { expires: 365 });
form1.submit();
}
}
});
</script>
Could please help me to solve it?
Calling:
$( '#demoSetSelected' ).ddslick( 'select', { index: i } );
will also trigger the "onSelected()" function you defined causing an infinite loop.
I solved the same problem by modifying the source file (jquery.ddslick.js) and adding a flag to disable the call to onSelected():
Change the select function to:
methods.select = function (options) {
return this.each(function () {
if (options.index)
selectIndex($(this), options.index, options.disableTrigger);
});
}
Modify selectIndex function definition from:
function selectIndex(obj, index) {
to:
function selectIndex(obj, index, disableTrigger) {
At the very end of the function selectIndex(...), change from:
if (typeof settings.onSelected == 'function') {
settings.onSelected.call(this, pluginData);
}
to:
if ( !disableTrigger ) {
if (typeof settings.onSelected == 'function') {
settings.onSelected.call(this, pluginData);
}
}
Then use instead:
$( '#demoSetSelected' ).ddslick( 'select', { index: i, disableTrigger: true } );
As an aside: to select by value instead of index, check out the code mentioned in:
https://github.com/prashantchaudhary/ddslick/issues/78
https://github.com/lunrfarsde/ddslick
It's a fork of dd-slick with the description part removed. But added select by value.
You may use plugin's select method like
$('#demoSetSelected').ddslick('select', {index: i });
to select a particular index.
As per ddSlick demo#4 on their website(http://designwithpc.com/plugins/ddslick#demo)

jQuery DataTable Undefined

I have two DataTables defined in $(document).ready() as follows:
oProdTable1 = $('#productstable1').dataTable( {...} );
oProdTable2 = $('#productstable2').dataTable( {...} );
Outside of $(document).ready(), I try to reload them. When I put a breakpoint in the following success function, I find that oProdTable1 is defined, but oProdTable2 is undefined:
function addProduct(productLine) {
$.ajax({
type: "POST",
url: 'ajax-add-product.php',
data: { productLine: productLine},
success: function(data) {
oProdTable1.fnReloadAjax();
oProdTable2.fnReloadAjax();
}
});
}
I can't find a difference between the definitions of these two tables. I also am wondering why oProdTable1 does not need to be declared with "var", yet is defined. Any ideas?
EDIT: I should note that oProdTable1 appears correctly, but oProdTable2 requires me to click to sort by a column for the rows to appear.
EDIT2: I have tried putting addProduct() inside $(document).ready(). oProdTable1 is still undefined and oProdTable2 is still undefined. I tried putting oProdTable2 before oProdTable1 and now oProdTable1 doesn't even load and both tables are undefined!
EDIT3: Every DataTable in the code after oProdTable2 does not load and is undefined. I compared the oProdTable1 and oProdTable2 code using the Notepad++ compare plugin and cannot find any major differences such as missing braces that I think could cause this.
EDIT4: Here is the code for oProdTable2, which seems to be problematic:
oProdTable2 = $('#productstable2').dataTable( {
"aaSorting": [[ 1, "asc" ]],
"aoColumnDefs":[
{"aTargets":[0],"bSearchable":false,"bVisible": false},
{"aTargets":[1],"sWidth":"60px"},
{"aTargets":[2],"sWidth":"200px"},
{"aTargets":[3],"sWidth":"300px"},
{"aTargets":[4],"sWidth":"60px"},
{"aTargets":[5],"sWidth":"60px"},
{"aTargets":[6],"sWidth":"60px"},
{"aTargets":[7],"sWidth":"60px"},
{"aTargets":[8],"sWidth":"60px"},
{"aTargets":[9],"sWidth":"60px"},
{"aTargets":[10],"sWidth":"60px"},
{"aTargets":[11],"sWidth":"60px"},
{ "sClass": "usa", "aTargets": [ 4, 5 ] },
{ "sClass": "can", "aTargets": [ 6, 7 ] },
{ "sClass": "lat", "aTargets": [ 8, 9 ] },
],
"iDisplayLength": 100, //sets item limit for table
"bJQueryUI": true,
"bProcessing": true,
"bServerSide": true,
"bSortCellsTop": true,
//"bStateSave": true,
"bSortClasses": false,
"sDom": 'T<"clear">C<"fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix"lfr>t<"fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix"ip>',
"oTableTools": {
"sRowSelect": "single",
"sSwfPath": "/swf/copy_cvs_xls_pdf.swf",
"aButtons":
[
//"Add Product" button
{
"sExtends": "text",
"sButtonText": "Add Product",
"fnClick": function ( nButton, oConfig, oFlash ) {
addProduct("2");
}
},
{
"sExtends": "collection",
"sButtonText": "Export",
"aButtons": [ "copy","print","csv", "xls", "pdf" ]
}
]
},
'sAjaxSource': 'ajax-getproductstable.php',
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "productLine", "value": "2" } );
},
"fnInitComplete": function() {
var oSettings = $('#productstable2').dataTable().fnSettings();
for ( var i=0 ; i<oSettings.aoPreSearchCols.length ; i++ ){
if(oSettings.aoPreSearchCols[i].sSearch.length>0){
$("thead input")[i-1].value = oSettings.aoPreSearchCols[i].sSearch;
$("thead input")[i-1].className = "activefilter"; }
}
},
"fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
var id = aData[0];
$(this.fnGetTds(nRow)[1]).addClass("editable").addClass("ref");
$(this.fnGetTds(nRow)[2]).addClass("edit_area").addClass("name");
$(this.fnGetTds(nRow)[3]).addClass("edit_area").addClass("description");
$(this.fnGetTds(nRow)[4]).addClass("editable").addClass("price_rtl_usa");
$(this.fnGetTds(nRow)[5]).addClass("editable").addClass("price_dlr_usa");
$(this.fnGetTds(nRow)[6]).addClass("editable").addClass("price_rtl_can");
$(this.fnGetTds(nRow)[7]).addClass("editable").addClass("price_dlr_can");
$(this.fnGetTds(nRow)[8]).addClass("editable").addClass("price_rtl_lat");
$(this.fnGetTds(nRow)[9]).addClass("editable").addClass("price_dlr_lat");
$(this.fnGetTds(nRow)[10]).addClass("editable").addClass("ins_val_rtl_usa");
$(this.fnGetTds(nRow)[11]).addClass("editable").addClass("ins_val_dlr_usa");
$(this.fnGetTds(nRow)[12]).addClass("editable").addClass("ins_val_rtl_can");
$(this.fnGetTds(nRow)[13]).addClass("editable").addClass("ins_val_dlr_can");
$(this.fnGetTds(nRow)[14]).addClass("editable").addClass("net_l");
$(this.fnGetTds(nRow)[15]).addClass("editable").addClass("net_w");
$(this.fnGetTds(nRow)[16]).addClass("editable").addClass("net_h");
$(this.fnGetTds(nRow)[17]).addClass("editable").addClass("net_weight");
$(this.fnGetTds(nRow)[18]).addClass("editable").addClass("packed_l");
$(this.fnGetTds(nRow)[19]).addClass("editable").addClass("packed_w");
$(this.fnGetTds(nRow)[20]).addClass("editable").addClass("packed_h");
$(this.fnGetTds(nRow)[21]).addClass("editable").addClass("packed_weight");
$(this.fnGetTds(nRow)[22]).addClass("editable").addClass("customs_cost");
$(this.fnGetTds(nRow)[23]).addClass("editable").addClass("customs_desc");
$(this.fnGetTds(nRow)[24]).addClass("editable").addClass("customs_code");
$(this.fnGetTds(nRow)[25]).addClass("editable").addClass("customs_origin");
$(this.fnGetTds(nRow)[26]).addClass("edit_area").addClass("note");
$(nRow).attr("id", id);
return nRow;
},
"fnDrawCallback": function () {
// CODE FOR EDITABLE INLINES
$(".edit_area_w").editable('ajax-edit-product-inline.php', {
type : 'mce',
submit : 'OK',
indicator : "Saving...",
tooltip : 'Click to edit...',
width : '500px',
height : '100px',
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
var update = oProdTable2.fnUpdate( sValue, aPos[0], aPos[2], true, true);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
}
});
$('.editable').editable('ajax-edit-product-inline.php', {
event : "dblclick",
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
var update = oProdTable2.fnUpdate( sValue, aPos[0], aPos[2], true, true);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
},
"height": "14px"
} );
$('.edit_area').editable('ajax-edit-product-inline.php', {
event : "dblclick",
type : "textarea",
cancel : 'Cancel',
submit : 'OK',
indicator : '<img src="img/indicator.gif">',
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
oProdTable2.fnUpdate( sValue, aPos[0], aPos[2]);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
},
} );
$('.edit_select').editable('ajax-edit-product-inline.php', {
event : "dblclick",
loaddata: function ( value, settings ) {
return {
"pid": $(this).parent().attr("id")
};
},
loadurl : 'ajax-part-selects.php',
loadtype: "GET",
type : 'select',
submit : 'OK',
"callback": function( sValue, y ) {
$(this).removeClass('empty_edit');
$("#productstable tr").removeClass("just_edited");
$(this).parent().addClass("just_edited");
var aPos = oProdTable2.fnGetPosition( this );
oProdTable2.fnUpdate( sValue, aPos[0], aPos[2]);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oProdTable2.fnGetPosition( this )[2]
};
},
});
}
} );
$("#productstable2 .floating_filters input").keyup( function () {
// Filter on the column (the index) of this element
oProdTable2.fnFilter( this.value, $(".floating_filters input").index(this)+1 );
$(this).addClass("activefilter");
} );
$("#productstable2 .floating_filters input").each( function (i) {
asInitVals[i] = this.value;
} );
$("#productstable2 .floating_filters input").focus( function () {
if ( $(this).hasClass("search_init"))
{
this.className = "";
this.value = "";
}
} );
$("#productstable2 .floating_filters input").blur( function (i) {
if ( this.value == "" )
{
$(this).removeClass("activefilter");
$(this).addClass("search_init");
this.value = asInitVals[$(".floating_filters input").index(this)];
}
} );
I finally found the solution! The problem wasn't even with the javascript code, it was with the html. The table with the id "productstable2" had one less "td" than "th". I just needed to add an additional <td></td> to the list of "td"s.

Datatable tr click function

I want to do some operations after clicking a particular row. I followed the API and this is what I ended up with but the click event is not working.
$(document).ready(function() {
table = $('#employees').dataTable( {
"bJQueryUI": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "show_employee_processor.php",
"aoColumns": [
{ "sTitle": "Empoyee ID" },
{ "sTitle": "Last Name" },
{ "sTitle": "First Name" },
{ "sTitle": "BBan Number" },
]
} );
table.$('tr').click(function() {
var data = table.fnGetData( this );
alert(data);
});
} );
The datatable is getting drawn but the click event is not working. What am I missing?
try delegated event:
table.on('click','tr',function() {
var data = table.fnGetData( this );
alert(data);
});
or:
$('#employees').on('click','tr',function() {
var data = table.fnGetData( this );
alert(data);
});
$("#employees tr").click( function( e ) {
if ( $(this).hasClass('row_selected')==false ) {
table .$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
var data = table.fnGetData( this );
alert(data);
}
else{
$(this).removeClass('row_selected');
}
});
CSS>
#employees tr.row_selected{
background-color:#B5CCD2;
opacity:0.95;
font-weight:bold;
}

Categories