DataTable filter with Date range - javascript

I have 2 DataTable in one page for both DataTable I have added date range using
function filterDateRangeService(){
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var dateStart = moment($("#fromDateSer").val(),"DD/MM/YYYY");
var dateEnd = moment($("#toDateSer").val(),"DD/MM/YYYY");
var evalDate= moment(data[5],"DD/MM/YYYY");
console.log("dateStart +"+dateStart+" dateEnd "+dateEnd)
// console.log("insidde")
if (evalDate >= dateStart && evalDate <= dateEnd) {
return true;
}
else {
return false;
}
}
);
function filterDateRangePatient(){
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var dateStart = moment($("#fromDate").val(),"DD/MM/YYYY");
var dateEnd = moment($("#toDate").val(),"DD/MM/YYYY");
var evalDate= moment(data[6],"DD/MM/YYYY");
console.log("dateStart +"+dateStart+" dateEnd "+dateEnd)
// console.log("insidde")
if (evalDate >= dateStart && evalDate <= dateEnd) {
return true;
}
else {
return false;
}
}
);
Both the function are called when respective checkbox is clicked. Problem is when I use date range for first function it filters the table for specific Date range, but When i try to filter the other table with 2nd function, only first function is called, i.e which ever function is called first only that function is called each time.
Calling function Using:
$('input[name="radioFilter"]').click(function(){
filterFunction();
});
$('input[name="radioFilterSer"]').click(function(){
filterFunctionSer();
});
function filterFunction(){
//some functions..
filterDateRangePatient()
}
function filterFunctionSer(){
//some functions..
filterDateRangeService()
}
How to resolve this, Why is the first function which is called first is only being called later also, or any thing I am doing Wrong. Or is it because of return Statement.

What about write single function with params and use it on both functions
function filterFunction(){
//some functions..
filterDateRange($("#fromDateSer").val(), $("#toDateSer").val(), 5)
}
function filterFunctionSer(){
//some functions..
filterDateRange($("#fromDate").val(), $("#toDate").val(), 6)
}
And the filterDateRange Function: (Updated: Added search pop function)
function filterDateRange(from, to, num){
$.fn.dataTable.ext.search.pop();
$.fn.dataTable.ext.search.push(function( settings, data, dataIndex ) {
var dateStart = moment(from,"DD/MM/YYYY");
var dateEnd = moment(to,"DD/MM/YYYY");
var evalDate= moment(data[num],"DD/MM/YYYY");
console.log("dateStart +"+dateStart+" dateEnd "+dateEnd);
if (evalDate >= dateStart && evalDate <= dateEnd) {
return true;
}
else {
return false;
}
});
}
It will work.

Related

Jquery onsubmit Function Runs Twice

i have the following code :
$("#add-form").on("submit", function (e) {
var isValid = $('#add-form').data('bootstrapValidator').isValid();
if (isValid == null || !isValid) {
$('#add-form').data('bootstrapValidator').validate();
return false;
}
var number = 0;
e.preventDefault();
var DepartureDate = $("#DepartureDate").val();
var ArrivalDate = $("#ArrivalDate").val();
var ArrivalTime = $("#ArrivalTime").val();
var DepartureTime = $("#DepartureTime").val();
if (DepartureDate == ArrivalDate && DepartureTime == ArrivalTime)
{
var msg = "Departure time and Arrival time cant have the same value in the same day "
showSmallBoxMsg('#GetResource("Menu.ID.20")', msg,#((int)Common.Enums.AlertStatus.Failed));
$('#submitBtn').prop('disabled', false);
}
return false;
})
simply if the arrival time equals the departure time on the same day the form should not submit and views a message as you can see in the photo,https://ibb.co/1rBMP5h
but the problem is after the function executed and message shows, the function runs again and the message appears one more time https://ibb.co/9ch6WZ5,
why is that happening

Break table.rows().iterator() in DataTable in JS

I want to break DataTable() interations.
Here is my code
let allCheckboxChecked=true;
let table = $('#myTable').DataTable();
table.rows().iterator( 'row', function ( context, index ) {
if($(this.row(index).node()).find("input").is(":Checked")){
allCheckboxChecked=true;
}
else{
allCheckboxChecked=false;
**return true;** // This is not working...I want your help here
}
} );
Using nodes() instead of iterator()
table.rows().nodes().to$().find('input:not(:checked):first').length // 0 - all checked
or with each()
let allCheckboxChecked = true;
table.rows().nodes().to$().each(function () {
if (!$(this).find('input').is(':checked')) {
allCheckboxChecked = false;
return false;
}
})

jQuery Countdown Timer Multiple Instances

When using The Final Countdown jQuery timer, it's easy to make a timezone aware timer based on one of the examples they provide. But now I want to use multiple instances on one page and don't know how. The code they provide for using multiple instances is this:
HTML:
<div data-countdown="2016/01/01"></div>
<div data-countdown="2017/01/01"></div>
<div data-countdown="2018/01/01"></div>
<div data-countdown="2019/01/01"></div>
JS:
$('[data-countdown]').each(function() {
var $this = $(this), finalDate = $(this).data('countdown');
$this.countdown(finalDate, function(event) {
$this.html(event.strftime('%D days %H:%M:%S'));
});
});
Doesn't look to difficult but when trying to implement it into my code it just doesn't work. As you can see in my code it also uses a different format of showing the time. Can anyone show me the correct way to do it with an explanation? This is my code:
$(window).on('load', function () { "use strict";
var labels = ['weeks', 'days', 'hours', 'minutes', 'seconds'],
nextYear = moment.tz("2017-05-03 17:00", "America/Los_Angeles"),
template = _.template($('#main-countdown-template').html()),
currDate = '00:00:00:00:00',
nextDate = '00:00:00:00:00',
parser = /([0-9]{2})/gi,
$countdown = $('#main-countdown');
function strfobj(str) {
var parsed = str.match(parser),
obj = {};
labels.forEach(function (label, i) {
obj[label] = parsed[i];
});
return obj;
}
function diff(obj1, obj2) {
var diff = [];
labels.forEach(function (key) {
if (obj1[key] !== obj2[key]) {
diff.push(key);
}
});
return diff;
}
var initData = strfobj(currDate);
labels.forEach(function (label, i) {
$countdown.append(template({
curr: initData[label],
next: initData[label],
label: label
}));
});
$countdown.countdown(nextYear.toDate(), function (event) {
var newDate = event.strftime('%w:%d:%H:%M:%S'),
data;
if (newDate !== nextDate) {
currDate = nextDate;
nextDate = newDate;
data = {
'curr': strfobj(currDate),
'next': strfobj(nextDate)
};
diff(data.curr, data.next).forEach(function (label) {
var selector = '.%s'.replace(/%s/, label),
$node = $countdown.find(selector);
$node.removeClass('flip');
$node.find('.curr').text(data.curr[label]);
$node.find('.next').text(data.next[label]);
_.delay(function ($node) {
$node.addClass('flip');
}, 50, $node);
});
}
});
});

How do i add an class to a json datatable?

I want to get a button on the last datarecord called factuur. I would like to get a div or button there but how can i do this in an data array like this one.
I was thinking i should add an class to the td and replace the text in here with something like this:
$('.className').each(function(index, item){
$(item).html(yourButton html);
})
Someone knows how to do this or a better way to do this?I looked into this but cant figure out how to apply is on my json.
this is how my script looks like now:
<table id="oTable" border="1" class="table_tag">
<tr><thead>
<th>Ordernummer</th>
<th>Besteldatum</th>
<th>BTW</th>
<th>Totaalbedrag</th>
<th>Status</th>
<th>Verzonden</th>
<th>Factuur</th>
</thead></tr>
</table>
script:
$(function(){
// Basic Setup
var $tableSel = $('#oTable');
$tableSel.dataTable({
'aaData': data,
'aoColumns': [
{'mData': 'EAN'},
{'mData': 'Besteldatum'},
{'mData': 'BTW'},
{'mData': 'Totaalbedrag'},
{'mData': 'Status'},
{'mData': 'Verzonden'},
{'mData': 'Factuur'}
],
'sDom': ''
});
$('#filter').on('click', function(e){
e.preventDefault();
var startDate = $('#start').val(),
endDate = $('#end').val();
filterByDate(1, startDate, endDate);
$tableSel.dataTable().fnDraw();
});
// Clear the filter. Unlike normal filters in Datatables,
// custom filters need to be removed from the afnFiltering array.
$('#clearFilter').on('click', function(e){
e.preventDefault();
$.fn.dataTableExt.afnFiltering.length = 0;
$tableSel.dataTable().fnDraw();
});
});
/* Our main filter function
* We pass the column location, the start date, and the end date
*/
var filterByDate = function(column, startDate, endDate) {
// Custom filter syntax requires pushing the new filter to the global filter array
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
var rowDate = normalizeDate(aData[column]),
start = normalizeDate(startDate),
end = normalizeDate(endDate);
// If our date from the row is between the start and end
if (start <= rowDate && rowDate <= end) {
return true;
} else if (rowDate >= start && end === '' && start !== ''){
return true;
} else if (rowDate <= end && start === '' && end !== ''){
return true;
} else {
return false;
}
}
);
};
// converts date strings to a Date object, then normalized into a YYYYMMMDD format (ex: 20131220). Makes comparing dates easier. ex: 20131220 > 20121220
var normalizeDate = function(dateString) {
var date = new Date(dateString);
var normalized = date.getFullYear() + '' + (("0" + (date.getMonth() + 1)).slice(-2)) + '' + ("0" + date.getDate()).slice(-2);
return normalized;
}
var data = [
{
"EAN": "180199",
"Besteldatum": "2003-09-22",
"BTW": "€19,00",
"Totaalbedrag": "€109,00",
"Status": "Verzonden",
"Verzonden": "2003-09-22",
"Factuur": "here"
},
{
"EAN": "180200",
"Besteldatum": "2004-11-12",
"BTW": "€19,00",
"Totaalbedrag": "€109,00",
"Status": "Verzonden",
"Verzonden": "2003-09-22",
"Factuur": "here"
},
];
What about a selector for the last child of each TR?
$('tr:last-child').each(()=>{
$(this).append("<button>");
})

2 Javascript functions into 1 Form Input Box

HEAVILY EDITED:
I have a form which has this input field:
<input id="RR_No" type="text" size="15" name="RR_No" readonly></div></TD>
In that field, I need to put the date in the format:
DDMMYYYY
And a Serial Number that is 6 numbers long to make a number like this:
DDMMYYYYABCDEF
Here is the Javascript to make the date:
function autoDate () {
var tDay = new Date();
var tMonth = tDay.getMonth()+1;
var tDate = tDay.getDate();
if ( tMonth < 10) tMonth = "0"+tMonth;
if ( tDate < 10) tDate = "0"+tDate;
document.getElementById("RR_Date").value = tDate+"/"+tMonth+"/"+tDay.getFullYear();
document.getElementById("RR_No").value = tDate+""+tMonth+""+tDay.getFullYear();
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
autoDate();
});
Which works.
I then have this JavaScript that copies the Serial Number into the same Input box:
$(function(){
$("#copyCheck").change(function() {
if ($("#copyCheck:checked").length > 0) {
bindGroups();
} else {
unbindGroups();
}
});
});
var bindGroups = function() {
// First copy values
$("input[name='RR_No']").val($("input[name='S_Serial_No']").val());
// Then bind fields
$("input[name='S_Serial_No']").keyup(function() {
$("input[name='RR_S_No']").val($(this).val());
});
};
var unbindGroups = function() {
$("input[name='SN_No0']").unbind("keyup");
};
But this second code overwrites the date already in the Input box.
I need it to show beside the Date within the same Input box.
Hope this makes more sense.
Chris
When you concatenate these two fields into a new 3rd field, you need to add the values together...
$("input[name='ID_field']").val($("input[name='Date_field']").val() + $("input[name='Other-value_field']").val());
If the date is being generated dynamically...
var d = new Date();
$("input[name='ID_field']").val(d.getTime() + $("input[name='Other-value_field']").val());

Categories