I need to know how to make my search filter that is with the JS Datatable plugin do a search with the exact value, now when placing the value 1 for example, it returns the numbers 1, 21, 113, 41 etc. It is a simple code only I can not find how to do that ...
I hope you can help
$('#txtFolioFilter').on( 'keyup change clear', function () {
table
.columns(13)
**.search = ( this.value )**
.draw();
} );
You can do this with a custom search function. The following example assumes you are using the standard DataTables global search field - which can be selected using the following jQuery selector:
$('.dataTables_filter input')
Here is the function:
$(document).ready(function() {
var table = $('#example').DataTable( {
// your table initialization here
} );
$.fn.dataTable.ext.search.push(
function( settings, searchData, index, rowData, counter ) {
var searchTerm = $('.dataTables_filter input').val();
if (searchTerm.trim() === "") {
return true;
}
var exactMatch = false;
searchData.forEach(function (cellText) {
if (searchTerm === cellText) {
exactMatch = true;
}
});
return exactMatch;
}
);
} );
The following line captures all search events from the main search box:
$.fn.dataTable.ext.search.push(...)
A blank search term will return all records.
Otherwise, for each row, we check each field in the row, and return that row as matched if any of the fields exactly match the search term.
If you want to apply this "exact match" to only one column, then you can adjust the custom filter:
$.fn.dataTable.ext.search.push(
function( settings, searchData, index, rowData, counter ) {
var searchTerm = $('.dataTables_filter input').val();
if (searchTerm.trim() === "") {
return true;
}
var match = false;
searchData.forEach(function (cellText, index) {
if (index === 3) {
if (searchTerm === cellText) {
match = true;
}
} else {
// all other columns:
if (cellText.includes(searchTerm)) {
match = true;
}
}
});
return match;
}
);
With this approach, what rows are displayed will depend on what your data looks like across the entire row, of course.
Documentation for the search plug-in is here, for more background.
Related
This is the approach I have tried so far:
$("#ExportPDF").on("click", function() {
var datatable = $('#myTable').DataTable();
if (! datatable.data().any()) {
console.log( 'the table is actually empty' );
}
else{
var table = $('#myTable').DataTable().search('something');
table.button( '.buttons-pdf' ).trigger();
}
});
When my table is empty, it does not export anything, which is perfect for me.
Now when the table contains elements, I do a search on a keyword something; if items are found they export them. But when no information is found it still exports an empty PDF.
How to avoid exporting an empty PDF?
Check the returned array before triggering the button :
else {
var table = $('#myTable').DataTable().search('something');
if( table != "" ){
table.button('.buttons-pdf').trigger();
}
}
$('#tableid').dataTable({
"fnDrawCallback": function () {
var table = $('#tableid').DataTable();
if (table.data().length === 0)
table.buttons('.buttons-html5').attr('disabled', true);
else
table.buttons('.buttons-html5').attr('disabled', false);
}
});
I want to find a row that has a certain value in one of the cells and apply class. I managed to do that, but problem is that it works only when I get to the page where that value exists.
drawCallback: function( settings ) {
var data = table.rows({ page: 'all' }).data();
$(data).each( function (idx) {
var row = table.row( idx );
if ( row.data().username === 'miko55' ) {
row.nodes().to$().addClass( 'table-success' );
alert(idx);
}
} );
}
I tried with page:'all' but it doesn't change anything.
You need to use Datatables jumpToData() plugin to achieve this. Try this
//jump to particular row in a table
YOUR_TABLE.page.jumpToData('VALUE YOU ARE LOOKING FOR', 0);
//add you CSS class to the row
YOUR_TABLE.rows(function (idx, data, node) {
if(data.YOUR_VALUE === 'VALUE YOU ARE LOOKING FOR') {
return true;
}
}).nodes().to$().addClass('YOUR CSS CLASS');
I have this code to search data in my tables. I'm trying to add a class on the found rows. It works, however once the search input field is empty, it still keeps the class on the cells. Is there any quick way to remove the class once the search field is empty/found is false?
$(document).ready(function() {
$('#search').keyup(function() {
searchTable($(this).val());
});
});
function searchTable(inputVal) {
var table = $('.phonetable');
table.find('tr').each(function(index, row) {
var allCells = $(row).find('td');
if(allCells.length > 0) {
var found = false;
allCells.each(function(index, td) {
var regExp = new RegExp(inputVal, 'i');
if(regExp.test($(td).text())) {
found = true;
return false;
}
});
if(found == true) $(row).show() .addClass("searchhighlight");
else $(row).hide();
}
});
}
Check if the value is empty and if it is remove the value:
$('#search').keyup(function() {
var value = $(this).val();
if(value)
searchTable();
else
$('.phonetable tr td').removeClass("searchhighlight");
});
Also look how I traverse the table with $('.phonetable tr td'), you can do something similiar in your current code.
I have this code for autocomplete in an HTML input :
$("#myinput")
.bind("keydown", function(event) {
// don't navigate away from the field on tab when selecting an item
if (event.keyCode === $.ui.keyCode.TAB
&& $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
var results = [],
selectionStart = this.element[0].selectionStart
term = extractLast(request.term.substring(0, selectionStart));
if (term.length > 0) {
console.log(term);
if(/*input has string "where"*/)
results = $.ui.autocomplete.filter(table1, term);
else
results = $.ui.autocomplete.filter(table2, term);
}
response(results);
},
focus: function() {
return false; // prevent value inserted on focus
},
select: function(event, ui) {
var terms = split(this.value.substring(0, this.selectionStart));
terms.pop(); // remove the current input
terms.push(ui.item.value); // add the selected item
this.value =
$.trim(terms.join(" ") + this.value.substring(this.selectionStart)) + " ";
return false;
}
});
What I'm trying to do is if the input has string "where" in somewhere, then it will load autocomplete from table1, otherwise it will load from table2. How can I check if the input has that string? Thanks in advance.
You should use includes method.
var inputValue=$("#myinput").val();
if(inputValue.toLowerCase().includes("where")){
//rest of code
}
Another method is using indexOf method.
if(inputValue.indexOf("where")!==-1){
//rest of code
}
If you want to do this achievment using regex, you can use search method.
if(inputValue.search(/where/i)!==-1){
//rest of code
}
inputValue="awherea";
console.log(inputValue.search(/where/))
If you want the strongest browser support, use String#indexOf
if(this.value.indexOf('where') > -1) {
//doSomething
}
you can get your text value and use indexof to find it .
my_inp = $("#myinput").val();
if (my_inp.indexOf('where') > -1) {
console.log('yes');
}
Try with string#match method use the ternary operator for return true or false
And also Some of the More method
string.indexOf()
string.includes()
console.log('hello everyone'.match("hello") ? true : false)
For jquery you could use the contains() method
console.log($('p').is(':contains("hi")'))
console.log($('p').is(':contains("22")')) // not contains
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>hello hi</p>
I have read about filtering table plugins. What I'm searching for is like this popup window.
(source: staticflickr.com)
When the user starts typing in the search-box, the relevant channel/category (as selected on previous dropdown box) should filter up. Also some animated loading action should happen while the filter process is going on.
I am looking for jQuery plugins which will make my filter-job easier to implement.
I think it is to ambigous to have a plugin for it. Just do something like this:
function filter($rows, category, search) {
$rows.each(function() {
if (category == ($("td:eq(2)", this).text() || category == "all") && (search. === "" || $("td:eq(1)", this).text().indexOf(search) !== -1) {
$(":checkbox", this).removeAttr("disabled");
$(this).show();
}
else
$(this).hide(function(){
$(":checkbox", this).attr("disabled", "disabled");
});
});
}
$("select.category").change(function() {
filter ($(this).closest("form").find("tr"), $(this).val(), $(this).closest("form").find("input.search").val());
});
$("input.search").keyUp(function() {
filter ($(this).closest("form").find("tr"), $(this).closest("form").find("select.catagory").val(), $(this).val());
});
You may need to make a few adjustments in order to make it work with the exact format of html.
Update to make it into a PLUGIN
$.fn.filter_table = function(options) {
options = $.extend(options, {
show: $.noop(), //Callback when a row get shown
hide: $.noop(), // Callback when a row gets hidden
entries: "table tr", // Selector of items to filter.
map: {} //Required parameter
//TODO Add default ajustment parameters here to remove ambiguity and assumptions.
});
return this.each(function() {
var form = this;
function each(callback) {
for (var selector in options.map) {
var check = options.map[selector];
$(selector, form).each(function(){
callback.call(this, check);
});
}
}
function show(row) {
if (!$(row).is(":visible")) {
options.show.apply(row);
$(row).show();
}
}
function hide(row) {
if ($(row).is(":visible"))
$(row).hide(options.hide);
}
function run_filter() {
$(options.entries, form).each(function() {
var row = this, matched = true;
each(function(check) {
matched &= check.call(this, row);
});
matched ? show(this) : hide(this);
})
}
//Bind event handlers:
each(function() {
$(this).bind($(this).is(":text") ? "keyup" : "change", run_filter);
});
});
};
You can use this plugin as follows:
$("form").filter_table({
map: {
//These callback define if a row was matched:
"select.category": function(row) {
//this refers to the field, row refers to the row being checked.
return $(this).val() == "all" || $(this).val() == $("td:eq(2)", row).text();
},
"input.search": function(row) {
return $(this).val() == "" || $(this).val() == $("td:eq(1)", row).text();
}
},
entries: "tr:has(:checkbox)", //Filter all rows that contain a checkbox.
show: function() {
$(":checkbox", this).removeAttr("disabled");
},
hide: function() {
$(":checkbox", this).attr("disabled", "disabled");
}
});
Okay it should work once it was debugged. I haven't tested it. I think that part is up to you.
If your HTML looks like this:
<form id="filterForm">
<input type="text" id="filterBox">
<input type="submit" value="Filter">
</form>
<div id="checkboxContainer">
<label><input type="checkbox" id="checkbox123"> Checkbox 123</label>
</div>
You could do something like...
//Set variables so we only have to find each element once
var filterForm = $('#filterForm');
var filterBox = $('#filterBox');
var checkboxContainer = $('#checkboxContainer');
//Override the form submission
filterForm.submit(function() {
//Filter by what the label contains
checkboxContainer.find('label').each(function() {
//If the value of filterBox is NOT in the label
if ($(this).indexOf(filterBox.val()) == -1) {
//Hide the label (and the checkbox since it's inside the label)
$(this).hide();
} else {
//Show it in case it was hidden before
$(this).show();
}
});
//Prevent the form from submitting
return false;
});
You can use this tablesorterfilter plugin to achieve what you need
Working Fiddle
And also please have a look at http://datatables.net/
There are many options out there. Here is a good place to start: http://www.wokay.com/technology/32-useful-jquery-filter-and-sort-data-plugins-62033.html
Filtering like this isn't incredibly complicated. It may be worth looking at the source of a couple plugins that come close to what you want and then try to write your own. You'll learn a lot more if you do it yourself!