Custom column filter in Data Table - php

I have a data table having 15 columns. Am using a below filter script which showing all the values in the combo box. It showing combobox filter for all the columns. but actually I don't need it. I want it for 2,4,5,6,12 Columns.I am using DataTables 1.10.16.
$("#dTable tfoot th").each( function ( i ) {
if ($(this).text() !== '') {
var isStatusColumn = (($(this).text() == 'Status') ? true : false);
var select = $('<select><option value=""></option></select>')
.appendTo( $(this).empty() )
.on( 'change', function () {
var val = $(this).val();
table.column( i )
.search( val ? '^'+$(this).val()+'$' : val, true, false )
.draw();
} );
if (isStatusColumn) {
var statusItems = [];
table.column( i ).nodes().to$().each( function(d, j){
var thisStatus = $(j).attr("data-filter");
if($.inArray(thisStatus, statusItems) === -1) statusItems.push(thisStatus);
} );
statusItems.sort();
$.each( statusItems, function(i, item){
select.append( '<option value="'+item+'">'+item+'</option>' );
});
}
else {
table.column( i ).data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' );
} );
}
```
[![Actuall View of the table now][1]][1]
[![I want like this][2]][2]
[1]: https://i.stack.imgur.com/gVZiR.png
[2]: https://i.stack.imgur.com/fqGWI.png

You could add a dynamic class to each select, then just display:none with CSS.
var select = $('<select class="' + i + '"><option value=""></option></select>')
then...
.variableName1,
.variableName5,
.variableName6,
.variableName7,
.variableName8,
.variableName9 {
display:none;
}

Related

Lazy Load + Isotope adaptation

i tried to adapt the explanation from this post :
Lazy Load + Isotope
to my proper case :
http://40parallele.com/produits-test.php?id=4
but something is missing...
Here is my js code :
// Isotope
$j(window).load(function()
{
// lazyload
var $win = $(window);
var $imgs = $('img.lazy');
var $container = $j('#folio');
// calcul la taille des images
$imgs.each(function(index) {
var item_height = $(this).attr("height");
$(this).parent().parent().css("height",item_height);
});
if( $container.length )
{
$container.isotope(
{
itemSelector : '.folio-item'
});
var $optionSets = $j('#portfolio .folio-filter'),
$optionLinks = $optionSets.find('a');
$optionLinks.click(function()
{
var $this = $j(this);
// don't proceed if already selected
if ( $this.hasClass('selected') )
{
return false;
}
var $optionSet = $this.parents('.folio-filter');
$optionSet.find('.selected').removeClass('selected');
$this.addClass('selected');
// make option object dynamically, i.e. { filter: '.my-filter-class' }
var options = {},
key = $optionSet.attr('data-option-key'),
value = $this.attr('data-option-value');
// parse 'false' as false boolean
value = value === 'false' ? false : value;
options[ key ] = value;
if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' )
{
changeLayoutMode( $this, options );
} else {
// otherwise, apply new options
$container.isotope( options );
}
return false;
});
}
$container.isotope({
onLayout: function() {
$win.trigger("scroll");
}
});
/*OK*/
$imgs.lazyload({
failure_limit: Math.max($imgs.length - 1, 0)
});
});
$j(window).bind('resize', function(e)
{
window.RT = setTimeout(function() {$j('#folio').isotope('reLayout'); }, 800);
});
thanks for your help

How to implement Isotope with Pagination

I am trying to implement isotope with pagination on my WordPress site (which obviously is a problem for most people). I've come up with a scenario which may work if I can figure a few things out.
On my page, I have this part of my isotope script -
$('.goforward').click(function(event) {
var href = $(this).attr('href');
$('.isotope').empty();
$('.isotope').load(href +".html .isotope > *");
$( 'div.box' ).addClass( 'isotope-item' );
$container.append( $items ).isotope( 'insert', $items, true );
event.preventDefault();
});
Then I am using this pagination function which I modified from here to have the 'goforward' class --
function isotope_pagination($pages = '', $range = 2)
{
$showitems = ($range * 2)+1;
global $paged;
if(empty($paged)) $paged = 1;
if($pages == '')
{
global $wp_query;
$pages = $wp_query->max_num_pages;
if(!$pages)
{
$pages = 1;
}
}
if(1 != $pages)
{
echo "<div class='pagination'>";
for ($i=1; $i <= $pages; $i++)
{
if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
{
echo ($paged == $i)? "<a href='".get_pagenum_link($i)."' class='inactive goforward'>".$i."</a>":"<a href='".get_pagenum_link($i)."' class='inactive goforward' >".$i."</a>";
}
}
echo "</div>\n";
}
}
1st Problem - I'm having issues with the filtering/sorting. It filters fine for the first page, but doesn't sort. On the second page or any other page loaded it does not append/insert or even filter/sort when starting fresh on that page. Instead, when trying to do so it gives me this error --
Uncaught TypeError: Cannot read property '[object Array]' of undefined
2nd Problem - When loading the page fragments, there's a delay and the current page is still visible before the next page fragment is loaded in its place.
I know a lot of people have problems with isotope and pagination, usually, end up using infinite scroll even though isotope author does not recommend it.
So my theory is loading content via load() and have a callback of some sort to only display filtered items.
Any ideas on how to achieve this?
My entire isotope script ---
$(function () {
var selectChoice, updatePageState, updateFiltersFromObject,
$container = $('.isotope');
$items = $('.item');
////////////////////////////////////////////////////////////////////////////////////
/// EVENT HANDLERS
////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// Mark filtering element as active/inactive and trigger filters update
$('.js-filter').on( 'click', '[data-filter]', function (event) {
event.preventDefault();
selectChoice($(this), {click: true});
$container.trigger('filter-update');
});
//////////////////////////////////////////////////////
// Sort filtered (or not) elements
$('.js-sort').on('click', '[data-sort]', function (event) {
event.preventDefault();
selectChoice($(this), {click: true});
$container.trigger('filter-update');
});
//////////////////////////////////////////////////////
// Listen to filters update event and update Isotope filters based on the marked elements
$container.on('filter-update', function (event, opts) {
var filters, sorting, push;
opts = opts || {};
filters = $('.js-filter li.active a:not([data-filter="all"])').map(function () {
return $(this).data('filter');
}).toArray();
sorting = $('.js-sort li.active a').map(function () {
return $(this).data('sort');
}).toArray();
if (typeof opts.pushState == 'undefined' || opts.pushState) {
updatePageState(filters, sorting);
}
$container.isotope({
filter: filters.join(''),
sortBy: sorting
});
});
//////////////////////////////////////////////////////
// Set a handler for history state change
History.Adapter.bind(window, 'statechange', function () {
var state = History.getState();
updateFiltersFromObject(state.data);
$container.trigger('filter-update', {pushState: false});
});
////////////////////////////////////////////////////////////////////////////////////
/// HELPERS FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// Build an URI to get the query string to update the page history state
updatePageState = function (filters, sorting) {
var uri = new URI('');
$.each(filters, function (idx, filter) {
var match = /^\.([^-]+)-(.*)$/.exec(filter);
if (match && match.length == 3) {
uri.addSearch(match[1], match[2]);
}
});
$.each(sorting, function (idx, sort) {
uri.addSearch('sort', sort);
});
History.pushState(uri.search(true), null, uri.search() || '?');
};
//////////////////////////////////////////////////////
// Select the clicked (or from URL) choice in the dropdown menu
selectChoice = function ($link, opts) {
var $group = $link.closest('.btn-group'),
$li = $link.closest('li'),
mediumFilter = $group.length == 0;
if (mediumFilter) {
$group = $link.closest('.js-filter');
}
if (opts.click) {
$li.toggleClass('active');
} else {
$li.addClass('active');
}
$group.find('.active').not($li).removeClass('active');
if (!mediumFilter) {
if ($group.find('li.active').length == 0) {
$group.find('li:first-child').addClass('active');
}
$group.find('.selection').html($group.find('li.active a').first().html());
}
};
//////////////////////////////////////////////////////
// Update filters by the values in the current URL
updateFiltersFromObject = function (values) {
if ($.isEmptyObject(values)) {
$('.js-filter').each(function () {
selectChoice($(this).find('li').first(), {click: false});
});
selectChoice($('.js-sort').find('li').first(), {click: false});
} else {
$.each(values, function (key, val) {
val = typeof val == 'string' ? [val] : val;
$.each(val, function (idx, v) {
var $filter = $('[data-filter=".' + key + '-' + v + '"]'),
$sort = $('[data-sort="' + v + '"]');
if ($filter.length > 0) {
selectChoice($filter, {click: false});
} else if ($sort.length > 0) {
selectChoice($sort, {click: false});
}
});
});
}
};
////////////////////////////////////////////////////////////////////////////////////
/// Initialization
////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// Initialize Isotope
$container.imagesLoaded( function(){
$container.isotope({
masonry: { resizesContainer: true },
itemSelector: '.item',
getSortData: {
date: function ( itemElem ) {
var date = $( itemElem ).find('.thedate').text();
return parseInt( date.replace( /[\(\)]/g, '') );
},
area: function( itemElem ) { // function
var area = $( itemElem ).find('.thearea').text();
return parseInt( area.replace( /[\(\)]/g, '') );
},
price: function( itemElem ) { // function
var price = $( itemElem ).find('.theprice').text();
return parseInt( price.replace( /[\(\)]/g, '') );
}
}
});
var total = $(".next a:last").html();
var pgCount = 1;
var numPg = total;
pgCount++;
$('.goback').click(function() {
$('.isotope').empty();
$('.isotope').load("/page/<?php echo --$paged;?>/?<?php echo $_SERVER["QUERY_STRING"]; ?>.html .isotope > *");
$container.append( $items ).isotope( 'insert', $items, true );
$( 'div.box' ).addClass( 'isotope-item' );
});
$('.goforward').click(function(event) {
var href = $(this).attr('href');
$('.isotope').empty();
$('.isotope').load(href +".html .isotope > *");
$( 'div.box' ).addClass( 'isotope-item' );
$container.append( $items ).isotope( 'insert', $items, true );
event.preventDefault();
});
});
//////////////////////////////////////////////////////
// Initialize counters
$('.stat-count').each(function () {
var $count = $(this),
filter = $count.closest('[data-filter]').data('filter');
$count.html($(filter).length);
});
//////////////////////////////////////////////////////
// Set initial filters from URL
updateFiltersFromObject(new URI().search(true));
$container.trigger('filter-update', {pushState: false});
});
});
lazy loader works quite well,i've tried it myself
check codepen
you can also try:
var $container = $('#container').isotope({
itemSelector: itemSelector,
masonry: {
columnWidth: itemSelector,
isFitWidth: true
}
});
Have you checked the following link:
https://codepen.io/Igorxp5/pen/ojJLQE
It has a working example of isotope with pagination.
Have a look at the following block of code from the JS section:
var $container = $('#container').isotope({
itemSelector: itemSelector,
masonry: {
columnWidth: itemSelector,
isFitWidth: true
}
});
Check below link if usefull
https://mixitup.kunkalabs.com/extensions/pagination/
You can also use lazy loder for pagination.
Hope this'll help you
I think this will help you.
Refer this URL

How to keep select after jquery append

Ok guys here's the fiddle
http://jsfiddle.net/wKbXx/24/
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
if ($(this).is(':checked')) {
sel.append( $("<option />").val(this.value).text( this.id ) );
} else {
$('option[value=' + this.value + ']').remove();
}
});
});
What I need to do is to select two colors with the check boxes. Let say red, and blue. Then using the select, Mark one red and one blue. Then check green. I want it to keep the selected data. Right now once you select green it wipes that data. How can I do that?
UPDATED TO REFLECT WORKING ANSWER.. UPDATED FIDDLE TOO
I would go for a slightly different approach; instead of always resetting the select boxes, I would check whether the text in the changed checkbox is already contained in the select boxes. If it is, I would assume it's been unchecked and remove the option from the select boxes. Otherwise I would append just that new option to the select boxes.
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
if (sel.find('option').text().indexOf(this.id) > 0) {
$('option[value=' + this.value + ']').remove();
} else {
sel.append( $("<option />").val(this.value).text( this.id ) );
}
});
});
The downside with this version is that the order of the colors in the select boxes is determined by the order in which the checkboxes are clicked; with your version, the order of the colors in the select boxes is always the same as in the checkboxes.
(Hope that made sense.)
Here's a fiddle: http://jsfiddle.net/Niffler/0hLxzvh8/
This may be the answer to your question...
You should have your rewrite on top as well.
$(function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
sel.html( opt.clone().text( '[Select One]' ) );
$( 'input[name=q1]' ).on( 'change', function() {
if ($(this).is(':checked')) {
sel.append( $("<option />").val(this.value).text( this.id ) );
}
else {
//Remove where ID matches up
sel.children().remove();
}
if( sel.find( 'option' ).length > 1 ) {
if( sel.find( 'option' ).length === 2 ) {
sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
}
}
});
});
Cheers!
You need to get the value of the select box before you replace the options, then reset the value at the end.
$(function() {
$( 'input[name=q1]' ).on( 'change', function() {
var sel = $('[id^="comm"]'), opt = $( '<option/>' );
sel.each(function(){
sel.data('previous', sel.val());
});
// overwrite the existing options
sel.html( opt.clone().text( '[Select One]' ) );
$( 'input[name=q1]:checked' ).each( function() {
sel.append( $("<option />").val(this.value).text( this.id ) );
});
// if it had a value, set it back to that.
if ( currentValue != '' ){
sel.each(function(){
sel.val(sel.data('previous'));
});
} else {
if( sel.find( 'option' ).length > 1 ) {
if( sel.find( 'option' ).length === 2 ) {
sel.find( 'option' ).eq( 1 ).attr( 'selected',true );
}
}
}
});
});

AutoComplete Highligh Issue

I want to highlight matched characters in jquery autocomplete.
If i type GC,it give me below,which is OK
Green Community
Now i want G and C both to be bold/strong.
$('#9').autocomplete({
source: "auto_loc_name.php",
selectFirst: true,
minLength: 0,
select: function (event, ui) {
alert(ui.item.value);
}
});
I was using JQuery Autocomplete as a combobox and your needs work well with me and you can review the following code may be help you :
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var input,
self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "",
wrapper = $( "<span>" )
.addClass( "ui-combobox" )
.insertAfter( select );
input = $( "<input>" )
.appendTo( wrapper )
.val( value )
.addClass( "ui-state-default" )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.appendTo( wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// work around a bug (likely same cause as #5265)
$( this ).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
}
});
})( jQuery );
and I think your needs in the following part but I don't know how to use that in your code :
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
You can try something like this, based on code from jQueryUI: how can I custom-format the Autocomplete plug-in results?
function monkeyPatchAutocomplete() {
$.ui.autocomplete.prototype._renderItem = function (ul, item) {
var matchstring = [];
$.each(this.term.split(""), function(index, c){
matchstring.push("^"+c+"|\b"+c);
});
var output = item.label.replace(new RegExp("(" + matchstring.join("|") + ")", "gi"), '<span class="ui-menu-item-highlight">$1</span>');
return $("<li>")
.append($("<a>").html(output))
.appendTo(ul);
};
}
$(function () {
monkeyPatchAutocomplete();
});
May or may not work. The idea is to get a Regex string like ^G|\bG for each character. I'm sure this misses quite a few cases, so keep working on it.
Edit: working jFiddle. http://jsfiddle.net/9MC5M/ Like the code above but with a few bug fixes. The search is deliberatly broken, it just returns all items to showcase the highlighting.

how to pass hidden id using json in jquery ui autocomplete?

perhaps it is duplicate,but i can't found solution so i posted this question.I am use jquery ui for auto complete search box. it works fine but the problem is i want to search using id.example:when user type paris,i try to send city_id in mysql for search. so problem is how to pass hidden id with json?
here the code:
<input type="text" name="grno" id="grno" class="input" title="<?php echo $lng['vldgrno'];?>
jquery code:
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#grno" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "pages/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 1 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( "," );
alert(data.id);
return false;
}
});
});
</script>
autocomplete.php :
<?php
mysql_connect('localhost','root','');
mysql_select_db('school');
$return_arr = array();
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
//create select query
$query = "select `grno`,`first_name`,`student_id` from `tbl_student` where `grno` like '%".$term."%' or `first_name` like '%".$term."%'";
// Run the query
$result = mysql_query ($query);
$array = array();
while($obj = mysql_fetch_array($result)){
$array['name'] = $obj['first_name']."(".$obj['grno'].")";
array_push($return_arr,$obj['first_name']."(".$obj['grno'].")");
}
$json = json_encode($return_arr);
echo $json;
?>
so.how to pass student_id in autocomplete.php,like label and value.{label='xyz' value='1'}
In autocomplete.php replace this code
array_push($return_arr,array("value"=>$obj['student_id'],"label"=>$obj['first_name']."(".$obj['grno'].")"));
and in your script change this
terms.push( ui.item.label );
$( "#stud_id" ).val( ui.item.value );
hope,this is what you find.

Categories