How to combine two JavaScript code blocks - javascript

I am new on javascript and I am trying to combine 2 javascript blocks but I am falling apart?
FIRST BLOCK
<script>
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('table.table tfoot th').each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="'+title+' ARA" />' );
} );
// DataTable
var table = $('table.table').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();
}
} );
} );
} );
</script>
SECOND BLOCK
$('table.table').DataTable({
"order": [
[0, "desc"]
],
paging: true,
"oLanguage": {
"sUrl": "js/dil/LANGUAGE.json",
}
} );
I want to add "oLanguage" and "order" lines to first javascript. What should I do?

Just copy-paste array from DataTables to first part:
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('table.table tfoot th').each(function () {
$(this).html('<input type="text" placeholder="'+$(this).text()+' ARA" />');
});
// DataTable
var table = $('table.table').DataTable({
order: [
[0, "desc"]
],
paging: true,
oLanguage: {
sUrl: "js/dil/LANGUAGE.json",
}
});
// 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();
}
});
});
});
Note DataTables used to have it's variables in hUngarianNotation and later on moved to camlCase, so it's most likely your oLanguage is not recognized by new API

Related

jQuery - Duplicate Fields & Autocomplete

I have a form with duplicate fields including autocomplete input.
The issue is : when i duplicate the fields, the autocomplete doesn't work on the new fields.
I spent time googling my issue and often it's a clone('true') issue, which i don't use already and still have the problem.
Can you help me please ? Thanks a lot !
I made a JSFiddle : https://jsfiddle.net/vqnaedvx/
Try with the letter j or s
HTML :
<div id="projects" class="content">
<button type="button" id="btnAdd" class="btn btn-primary btn-sm">Add Project</button>
<div class="row form-group group">
<input class="project-label">
<input type="hidden" class="project-id">
<button type="button" class="btn btn-danger btnRemove">Remove</button>
</div>
</div>
JS Multifield :
/**
* jQuery Multifield plugin
*
* https://github.com/maxkostinevich/jquery-multifield
*/
;(function ( $, window, document, undefined ) {
// our plugin constructor
var multiField = function( elem, options ){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
// Localization
this.localize_i18n={
"multiField": {
"messages": {
"removeConfirmation": "Are you sure you want to remove this section?"
}
}
};
this.metadata = this.$elem.data( 'mfield-options' );
};
// the plugin prototype
multiField.prototype = {
defaults: {
max: 0,
locale: 'default'
},
init: function() {
var $this = this; //Plugin object
// Introduce defaults that can be extended either
// globally or using an object literal.
this.config = $.extend({}, this.defaults, this.options,
this.metadata);
// Load localization object
if(this.config.locale !== 'default'){
$this.localize_i18n = this.config.locale;
}
// Hide 'Remove' buttons if only one section exists
if(this.getSectionsCount()<2) {
$(this.config.btnRemove, this.$elem).hide();
}
// Add section
this.$elem.on('click',this.config.btnAdd,function(e){
e.preventDefault();
$this.cloneSection();
});
// Remove section
this.$elem.on('click',this.config.btnRemove,function(e){
e.preventDefault();
var currentSection=$(e.target.closest($this.config.section));
$this.removeSection(currentSection);
});
return this;
},
/*
* Add new section
*/
cloneSection : function() {
// Allow to add only allowed max count of sections
if((this.config.max!==0)&&(this.getSectionsCount()+1)>this.config.max){
return false;
}
// Clone last section
var newChild = $(this.config.section, this.$elem).last().clone().attr('style', '').attr('id', '').fadeIn('fast');
// Clear input values
$('input[type=text],input[type=hidden],textarea', newChild).each(function () {
$(this).val('');
});
// Fix radio buttons: update name [i] to [i+1]
newChild.find('input[type="radio"]').each(function(){var name=$(this).attr('name');$(this).attr('name',name.replace(/([0-9]+)/g,1*(name.match(/([0-9]+)/g))+1));});
// Reset radio button selection
$('input[type=radio]',newChild).attr('checked', false);
// Clear images src with reset-image-src class
$('img.reset-image-src', newChild).each(function () {
$(this).attr('src', '');
});
// Append new section
this.$elem.append(newChild);
// Show 'remove' button
$(this.config.btnRemove, this.$elem).show();
},
/*
* Remove existing section
*/
removeSection : function(section){
if (confirm(this.localize_i18n.multiField.messages.removeConfirmation)){
var sectionsCount = this.getSectionsCount();
if(sectionsCount<=2){
$(this.config.btnRemove,this.$elem).hide();
}
section.slideUp('fast', function () {$(this).detach();});
}
},
/*
* Get sections count
*/
getSectionsCount: function(){
return this.$elem.children(this.config.section).length;
}
};
multiField.defaults = multiField.prototype.defaults;
$.fn.multifield = function(options) {
return this.each(function() {
new multiField(this, options).init();
});
};
})( jQuery, window, document );
$('#projects').multifield({
section: '.group',
btnAdd:'#btnAdd',
btnRemove:'.btnRemove'
});
JS Autocomplete :
$( function() {
var projects = [
{
value: "jquery",
label: "jQuery"
},
{
value: "jquery-ui",
label: "jQuery UI"
},
{
value: "sizzlejs",
label: "Sizzle JS"
}
];
$( ".project-label" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( ".project-label" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( ".project-label" ).val( ui.item.label );
$( ".project-id" ).val( ui.item.value );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
};
} );
you have 2 probs here:
1.Your code only for one input textfield. if u add more textfields, all value of textfields will have the same value. u need call autocomplete in foreach
2.After u press add input jquery not call autocomplete again(new input doesn't have autocomplete). So you need call it after new input added.
fixed here:
declare global function:
/**
* jQuery Autocomplete
*/
$( function() {
var projects = [
{
value: "jquery",
label: "jQuery"
},
{
value: "jquery-ui",
label: "jQuery UI"
},
{
value: "sizzlejs",
label: "Sizzle JS"
}
];
refreshAuto = function(){
$(".project-label").each(function(idx,ele){
var item = $(ele);
item.autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
item.val( ui.item.label );
return false;
},
select: function( event, ui ) {
item.val( ui.item.label );
item.attr('id',ui.item.value);
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
};
});
}
refreshAuto(); // call to init once
} );
at "jQuery Multifield plugin" find '// Add section' add the line so:
// Add section
this.$elem.on('click',this.config.btnAdd,function(e){
e.preventDefault();
$this.cloneSection();
refreshAuto(); //call autocomplete new input
});
hope this help !

Tooltip does not work with pagination on datatables

How can I get my tooltip being displayed when using pagination within the datatable plugin?
I am using the plugin protip in connection with datatables to display tooltips, when text inside a column is too long. The tooltips plugin already works with the following snippet:
//Datatable Setup
jQuery(document).ready(function($) {
var table = $('#irp-table.raab').DataTable({
"columnDefs": [
{ visible: false, targets: 2 },
{ className: 'mdl-data-table__cell--non-numeric', targets: [0, 1]}
],
"order": [[ 0, 'asc' ]],
"displayLength": 25,
"drawCallback": function ( settings ) {
var api = this.api();
var rows = api.rows( {page:'current'} ).nodes();
var last=null;
api.column(2, {page:'current'} ).data().each( function ( group, i ) {
if ( last !== group ) {
$(rows).eq( i ).before(
'<tr class="group"><td colspan="3">'+group+'</td></tr>'
);
last = group;
}
} );
}
} );
//Initialize ToolTip
jQuery(document).ready(function($) {
$.protip();
});
//ToolTip hover behaviour
jQuery(document).ready(function($) {
$('td').bind('mouseenter', function () {
var $this = $(this);
if (this.offsetWidth < this.scrollWidth) {
var text = $this.text();
$this.attr("data-pt-title", text);
$this.protipShow()
}
}).mouseenter();
});
However it just works on the first site for the case I am using pagination on my datatable and navigate to another site.
SOLUTION
You need to use drawCallback to initialize tooltips every time DataTables redraws the table. This is needed because TR and TD elements for pages other than first are not present in DOM at the time first page is displayed.
Also the call to mouseenter() is not needed.
For example:
"drawCallback": function ( settings ) {
var api = this.api();
// ... skipped ...
$.protip();
$('td', api.table().container()).on('mouseenter', function () {
var $this = $(this);
if (this.offsetWidth < this.scrollWidth) {
var text = $this.text();
$this.attr("data-pt-title", text);
$this.protipShow();
}
});
}
LINKS
See jQuery DataTables: Custom control does not work on second page and after for more examples and details.

Datatable cannot get row index after search

I have create a datatable and can get the row index of the data before any search action.
dataArray=[
[1, "Name1"],
[2, "Name2"], ,
[3, "Name23"],
];
var table = $('#tblName').DataTable( {
scrollY: '40vh',
"scrollX": true,
scrollCollapse: true,
paging: false,
responsive:true,
data: dataArray,
} );
$('#tblName tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected1') ) {
}
else
{
$('#tblName tbody tr ').each( function () {
if ( $(this).hasClass('selected1') ) {
$(this).removeClass('selected1');
}
} );
$(this).addClass('selected1');
}
} );
I want to get the row index to change the value of the dataArray . The following is the input text searchName to filter the datatable with keyword match with dataArray in column 1
$('#searchName').on( 'keyup', function () {
table
.columns( 1 )
.search( this.value )
.draw();
} );
$('#tblName tbody').on( 'click', 'tr', function () {
$('#tblName tbody tr ').each( function () {
if ( $(this).hasClass('selected1') ) {
var rowindex=$(this).closest('tr').index();
var dataWareHouse = table.row( this ).columns(1).data();
var selectedName = dataArray[0][rowindex];
console.log(selectedName);
}
} );
} );
After filter the datatable with input text searchName, I cannot get the correct old row Index. For example input in searchName:
2
The datable will show only 2 row with Name of Name2 and Name23,
However, when i click the first row, it show the Name1. The correct return data should be Name2
Well, you can't rely on DOM index when you are using search. Since some data will not be displayed due to filtering. But DataTable provide API method to get correct indices, data, etc.
$('#tblName tbody').on( 'click', 'tr', function () {
$('#tblName tbody tr ').each( function () {
if ( $(this).hasClass('selected1') ) {
var rowindex = table.row(this).index();
var rowData = table.row(this).data();
var selectedName = table.row(this)[0];
var anotherWayToGetName = table.cell(rowIndex, 0).data();
console.log(rowIndex, rowData, selectedName, anotherWayToGeName);
}
} );
} );

Datatables inline editing with datepicker

Ok so I have this datatable with around 90 fields being populated from a dbContext (Visual Studio MVC4). I added the .makeEditable() to enjoy inline editing...
Most of my fields are of a type string (but a user CAN input a date if he opts to....even though its a text type field, the date will be input as simple text..)
The problem I have is that even though I'm successfully being able to get the class of the edit form to become "datepicker", the calender isn't popping up and on other simple non-datatable pages, it runs just fine.
I want to be able to set certain column cells to have inline datepicking ability..
I want my table to look like this thing http://jquery-datatables-editable.googlecode.com/svn/trunk/inline-edit-extra.html
I tried mimic-ing the code there but with no success....its always a textbox for editing instead of a calender view..
UPDATE: I noticed that if I change the "type:" field in
$.fn.editable.defaults = {
name: 'value',
id: 'id',
type: 'datepicker',
width: 'auto',
height: 'auto',
event: 'click.editable',
onblur: 'cancel',
loadtype: 'GET',
loadtext: 'Loading...',
placeholder: 'Double-Click to edit',
loaddata: {},
submitdata: {},
ajaxoptions: {}
};
My entire table gets a datepicker on editing mode...
Apparently the intializing code to give certain columns datepicker options doesn't work as it should ....or at least I guess so
**UPDATE END****
This is my datatable initialization code:
<script language="javascript" type="text/javascript">
$(function() {
$(".datepicker").datepicker({ dateFormat: 'dd-MM-yy' });
});
$(document).ready(function ()
{
$('#myDataTable thead tr#filterrow th').each(function () {
var title = $('#myDataTable thead th').eq($(this).index()).text();
$(this).html('<input type="text" onclick="stopPropagation(event);" placeholder="Search ' + title + '""style="direction: ltr; text-align:left;" />');
});
$("#myDataTable thead input").on('keyup change', function () {
table
.column($(this).parent().index() + ':visible')
.search(this.value)
.draw();
});
var table = $('#myDataTable').DataTable({
//"scrollY": "200",
"scroller": "true",
"deferRender": "true",
"orderCellsTop": "true",
"columnDefs": [
{ "visible": false, "targets": 1 },
{ "type": "datepicker", "aTargets": [6,7,8,9,10] },
{ 'sClass':"datepicker", "aTargets": [6, 7, 8, 9, 10] }
],
"order": [[1, 'asc']],
"displayLength": 25,
"drawCallback": function (settings)
{
$(".datepicker").datepicker({ dateFormat: 'dd-MM-yy' });
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(1, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="88">' + group + '</td></tr>'
);
last = group;
}
});
},
"fndrawCallback": function (settings) {
$(".datepicker").datepicker({ dateFormat: 'dd-MM-yy' });
}
});
// Apply the search
table.columns().every(function () {
var that = this;
$('input', this.header()).on('keyup change', function () {
that
.search(this.value)
.draw();
});
});
// Order by the grouping
$('#myDataTable tbody').on('click', 'tr.group', function () {
var currentOrder = table.order()[0];
if (currentOrder[0] === 1 && currentOrder[1] === 'asc') {
table.order([1, 'desc']).draw();
}
else {
table.order([1, 'asc']).draw();
}
});
//$('#myDataTable thead').append($('#myDataTable thead tr:eq(0)')[0]);
$('#myDataTable').dataTable().makeEditable({
"aoColumnDefs": [
{ "type": "hasDatepicker", "aTargets": 4 },
{ "sClass": "hasDatepicker", "aTargets": 4 }
]
});
});
function stopPropagation(evt) {
if (evt.stopPropagation !== undefined) {
evt.stopPropagation();
} else {
evt.cancelBubble = true;
}
}
this is the datepicker.js
// add :focus selector
jQuery.expr[':'].focus = function (elem) {
return elem === document.activeElement && (elem.type || elem.href);
};
$.editable.addInputType(' datepicker', {
/* create input element */
element: function (settings, original) {
var form = $(this),
input = $('class ="datepicker" <input />');
// input.attr('class', 'datepicker');
input.attr('autocomplete', 'off');
form.append(input);
return input;
},
/* attach jquery.ui.datepicker to the input element */
plugin: function (settings, original) {
var form = this,
input = form.find("input");
// Don't cancel inline editing onblur to allow clicking datepicker
settings.onblur = 'nothing';
datepicker = {
onSelect: function () {
// clicking specific day in the calendar should
// submit the form and close the input field
form.submit();
},
onClose: function () {
setTimeout(function () {
if (!input.is(':focus')) {
// input has NO focus after 150ms which means
// calendar was closed due to click outside of it
// so let's close the input field without saving
original.reset(form);
} else {
// input still HAS focus after 150ms which means
// calendar was closed due to Enter in the input field
// so lets submit the form and close the input field
form.submit();
}
// the delay is necessary; calendar must be already
// closed for the above :focus checking to work properly;
// without a delay the form is submitted in all scenarios, which is wrong
}, 150);
}
};
if (settings.datepicker) {
jQuery.extend(datepicker, settings.datepicker);
}
input.datepicker(datepicker);
}
});
So after a lot of trial and error.....
I manually input the type of each of my 90 columns, and it manually worked....columnDefs with targeting a list of columns is probably bugged as in jeditable.datepicker it doesn't parse a list of columns passedin the settings....
Hope this helps a lost soul later on...

Clone a selected row in DataTables?

I am currently able to delete a selected row, and now I want to duplicate/clone the selected row. Sometimes adding rows to DataTables can be tricky because the pagination will not update, so clone and append.
http://jsfiddle.net/BWCBX/30/
jQuery
var oTable;
/* Add a click handler to the rows - this could be used as a callback */
$("#example tbody tr").click( function( e ) {
if ( $(this).hasClass('row_selected') ) {
$(this).removeClass('row_selected');
}
else {
oTable.$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
}
});
/* Add a click handler for the delete row */
$('#delete').click( function() {
var anSelected = fnGetSelected( oTable );
if ( anSelected.length !== 0 ) {
oTable.fnDeleteRow( anSelected[0] );
}
} );
/* Init the table */
oTable = $('#example').dataTable( );
/* Get the rows which are currently selected */
function fnGetSelected( oTableLocal )
{
return oTableLocal.$('tr.row_selected');
}
In order to respect paging of jquery datatables the clone method should be calling the fnAddData function,
$('#clone').click( function() {
var anSelected = fnGetSelected( oTable );
console.log(anSelected);
var data=[];
$(anSelected).find('td').each(function(){data.push($(this).text());});
oTable.fnAddData( data );
} );
http://jsfiddle.net/BWCBX/32/
You need to add the click listener for selecting to these new rows as well.
For example,
$('#clone').click( function() {
var anSelected = fnGetSelected( oTable );
var data=[];
$(anSelected).find('td').each(function(){data.push($(this).html());});
var row=oTable.fnAddData( data );//returns the index of the row added
$(oTable.fnGetNodes(row)).click( function( e ) {
if ( $(this).hasClass('row_selected') ) {
$(this).removeClass('row_selected');
}
else {
oTable.$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
}
});
} );
http://jsfiddle.net/BWCBX/33/
I implemented using the .clone() jQuery, see: jsfiddle
$('#clone').click(function(){
var anSelected = fnGetSelected( oTable );
anSelected.clone().insertAfter( $("table").find("tr").last());
$("table").find("tr").last().removeClass("row_selected");
});
Hope this help

Categories