How to filter dropdown list in angular md-option when scope value is changing - javascript

I have a dropdown menu using with the data array
data = [{type:"day", value:"daily"}
,{type:"hour", value:"hourly"}
,{type:"month", value:"monthly"}]
and also i have flag in my environment variable as
enableHourly = "true"
enableDaily = "true"
enableMonthly = "true"
by setting one of the value in false
the value should be change like
if enableHourly = "false"
in the md-options select should only display day and month
this is what i try but it seems its not working atm.
self.timeExecutionList = () => {
// check if hourly, daily, weekly, monthly tag is true or false string then remove to
// the array
if (self.beebotCreate) {
var arr = self.timeTypeList;
for( var i = 0, n = arr.length; i < n; i++){
if (arr[i].includes('hr') && self.beebotRunHourly !== "true") {
arr.splice(i, 1);
}
if (arr[i].type === 'day' && self.beebotRunTimeOfDay !== "true") {
arr.splice(i, 1);
}
if (arr[i].type === 'week' && self.beebotRunMonthly !== "true") {
arr.splice(i, 1);
}
if (arr[i].type === 'month' && self.beebotRunMonthly !== "true") {
arr.splice(i, 1);
}
i--
}
return arr
}
if you have cleaner solution would be appreaciated

I feel you could add the boolean value to the data field with default settings and make use of the boolean variable to populate the dropdown. slicing array is expensive.
data = [{type:"day", value:"daily", "enabled" : true}
,{type:"hour", value:"hourly","enabled" : true}
,{type:"month", value:"monthly", "enabled" : true}]
In html, for all options, if the flag is set to true, add it to dropdown else not. Hope that helps
<md-select>
<div ng-repeat="type in data" >
<md-option *ngIf="type.enabled" ng-value="{{value}}">
{{type.value}}
</md-option>
</div>
</md-select>`

Related

How to make the dropdown option of a select box

I'm building a train web booking project. Now I need to build a selectbox and the option value is varied based on the booking form.
//select-box
<custom-select-box
label="Travel"
v-model="form.InfantWithAdult"
:items="travel"
></custom-select-box>
Try with forEach:
travelWith() {
let travellerlist = [];
let adults = this.passengers.filter(
(x) =>
x.PaxType === "ADT" &&
x.SSR.Outbound.filter((y) => {
return y.codeType === "INFT";
}).length > 0
);
if (adults.length > 0) {
let nr = 1;
let travel = null;
// 👇 loop all adults and add to travellerlist array
adults.forEach(adult => {
if (!adult.FirstName) {
travel = `Adult ${nr++}`;
} else if (adult.FirstName !== "" && adult.LastName !== "") {
travel = `Adult ${nr++} ${adult.Title} ${adult.FirstName} ${adult.LastName}`;
}
travellerlist.push(travel);
})
}
return travellerlist;
},

How to add one and more leaves in jquery datepicker

I add leave in datepicker using array but, two leave is on same day is not showing in calendar only first leave in array is showing but second leave is not showing.
my var leaveday array is like this = "2021,09,28,Love is on Leave-2021,09,18,Pravin is on Leave-2021,09,25,Darshit is on Leave-2021,09,18,Love is on Leave-"
my jquery is here
var leave_dates= $("#all_past_leave").val();
if(leave_dates !== null && leave_dates !== '' && leave_dates !== undefined) {
var leave_all = leave_dates.slice(0,-1);
var leaveDays = leave_all.split('-');
}
$(function() {
$("#past_leave").datepicker({
numberOfMonths:3,
beforeShowDay: setLeaveDays
});
// set Leave function which is configured in beforeShowDay
function setLeaveDays(date) {
for (i = 0; i < leaveDays.length; i++) {
var leaveData = leaveDays[i].split(',');
if (date.getFullYear() == leaveData[0]
&& date.getMonth() == leaveData[1] - 1
&& date.getDate() == leaveData[2]) {
return [true, 'staff_leaves', leaveData[3]];
}
}
return [true, ''];
}
});
I am getting result like this see image here
but I want result like this I edited from chrome inspect for example see image here

Lost part of page after post page

After clicking start in this page, the value is lost.
What can I do, in order not to make the page reload itself?
<button onclick="start()">Start</button>
Start: this is called when the user clicks start on the setup screen
function start(reuse){
reuse = (typeof reuse === 'undefined') ? false : true;
//user input is read
numberOfQuestions = $("#amount").val();
time = $("#time").val();
showError = $("#showError").prop("checked");
showCorrect = $("#showCorrect").prop("checked");
fullscreen = $("#fullscreen").prop("checked");
//currentIndex is the index of current question in the list while in the quiz
currentIndex = -1;
//reset correct questions
correct = 0;
var pred = {place:1, time:2, other:3};
var _numberOfQuestions = 0;
if (reuse){
_data = filteredData;
} else {
_data = data;
}
//filteredData is the new list of question AFTER filtering it according to setup screen
filteredData = [];
$.each(_shuffle(_data), function(index, entry){
if ($("#ddcl-d1-i"+entry['pad']).prop("checked")){
if ($("#ddcl-d2-i"+pred[entry['pred']]).prop("checked")){
_numberOfQuestions++;
entry['a'] = _shuffle(entry['a']);
filteredData.push(entry);
}
}
if (_numberOfQuestions == numberOfQuestions) return false;
});
if (_numberOfQuestions == 0){
alert("No questions available");
return;
}
$("#quiz").show();
$("#setup").hide();
$("#finish").hide();
secondsLeft = time * numberOfQuestions;
doTimer();
nextQuestion();
if (fullscreen && screenfull.enabled){
screenfull.request(document.getElementById('container'));
}
}
I call Start with JavaScript.
I try to add autopostback ="false", but the outcome remains the same.
You can add type attribute to buttons, because they automatically submit forms.
<button type="button" onclick="start()">Start</button>

Number elements by class and get placement of specific div

I have a list like this:
<div class="list"></div>
<div class="list"></div>
<div class="list on"></div>
<div class="list"></div>
... etc
I get the total like this:
var count = $('.list').length; // 4 in this case
But I want to write a function that selects the next div with the down arrow, and I can't figure out how to get the next div, select it, and deselect the current div. This is what I have now, but it doesn't work:
var visible = $('.list:visible');
var on = $('.list.on:visible');
if (e.keyCode == 40) { // down key
if(on.length == 0) {
visible.first().addClass("on"); // this works
}
else if( // div placement // < count) {
var next = on.next(); // this part doesn't work
on.removeClass("on"); // :(
next.addClass("on"); // :(
}
else { // if its the last div
// do nothing
}
}
You can do:
if (e.keyCode == 40) { // down key
if(on.length == 0) {
visible.first().addClass("on");
}
else if(on.length && on.next("div.list").length > 0) {
var next = on.next("div.list");
on.removeClass("on");
next.addClass("on");
}
else { // if its the last div
// do nothing
}
}
A quick demo: http://jsfiddle.net/GL7tA/
You can work with .index() to see which item is currently "selected":
var $items = $('.list:visible'),
$selectedItem = $items.filter('.on'),
selectedIndex = $items.index($selectedItem);
if (selectedIndex == -1) {
$items.eq(0).addClass('on');
} else if (selectedIndex + 1 < $items.length) {
$selectedItem.next().andSelf().toggleClass('on');
}
You have a syntax error in the else if ( part, where you say it doesn't work.
It doesn't work because the else if is expecting a condition to evaluate but you are not even closing the parenthesis of that if condition, neither have you openned the brackets for its block.

My DataTables date range filter using jQuery UI Datepicker works only in Google Chrome

I feel like I could use another pair of eyes on my code right now.
I am using jQuery UI's Datepicker to grab dates from two html inputs:
<!-- HTML inputs -->
<p id="date_filter">
<span id="date-label-from" class="date-label"><?php echo LANG_FROMDATE; ?>: </span><input class="date_range_filter date" type="text" id="datepicker_min" /><img id="calender-from" class="datepicker-calender" src="includes/js/jquery/jquery-ui/img/calendar.png" width="17px" height="18px" />
<span id="date-label-to" class="date-label"><?php echo LANG_TODATE; ?>: </span><input class="date_range_filter date" type="text" id="datepicker_max" /><img id="calender-to" class="datepicker-calender" src="includes/js/jquery/jquery-ui/img/calendar.png" width="17px" height="18px" />
<button class="btn" id="reset_btn"><?php echo LANG_RESET; ?></button>
</p>
That calender img tag is just an icon that also triggers the datepicker, i.e. like this:
$(document).ready(function() {
$('#calender-from').click(function() {
$("#datepicker_min").datepicker("show");
});
$('#calender-to').click(function() {
$("#datepicker_max").datepicker("show");
});
});
So that's the basic stuff that's all good. The issue I'm having is I have written javascript that is an extension to the DataTables filtering api. I wrote my code based on this example: https://datatables.net/examples/plug-ins/range_filtering.html
The problem is right now my code is only working in Google Chrome and fails in FireFox, Safari, and Internet Explorer. I probably am just missing something small or have some minor semantic mistake in my code.
I extend the DataTables filtering API like this:
// Date range filter
var minDateFilter = "";
var maxDateFilter = "";
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
if ( typeof aData._date == 'undefined' ) {
aData._date = new Date(aData[0]).getTime();
}
if ( minDateFilter && !isNaN(minDateFilter) ) {
if ( aData._date < minDateFilter ) {
return false;
}
}
if ( maxDateFilter && !isNaN(maxDateFilter) ) {
if ( aData._date > maxDateFilter ) {
return false;
}
}
return true;
}
);
This way seems to return false in other browsers because I will get a result of "Showing 1 - 50 of 67 records" regardless of what data I have in the datapicker inputs.
I'm handling the jQuery UI Datepicker inputs like this:
$(document).ready(function() {
$("#datepicker_min").datepicker({
"onSelect": function(date) {
minDateFilter = new Date(date).getTime();
oTable.fnDraw();
}
}).keyup(function(){
minDateFilter = new Date(this.value).getTime();
oTable.fnDraw();
});
$( "#datepicker_max" ).datepicker( {
"onSelect": function(date) {
maxDateFilter = new Date(date).getTime();
oTable.fnDraw();
}
}).keyup(function(){
maxDateFilter = new Date(this.value).getTime();
oTable.fnDraw();
});
});
I also tried extending the filter API like this (to be closer to original DataTables example):
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
var iMin = minDateFilter;
var iMax = maxDateFilter;
var iDate = new Date(aData[0]).getTime();
if ( iMin == "" && iMax == "" )
{
return true;
}
else if ( iMin == "" && iDate < iMax )
{
console.log("iDate 1 = "+iDate);
return true;
}
else if ( iMin < iDate && "" == iMax )
{
console.log("iDate 2 = "+iDate);
return true;
}
else if ( iMin < iDate && iDate < iMax )
{
console.log("iDate = 3 "+iDate);
return true;
}
return false;
}
);
When I do it this way I get a somewhat similar result of my filter code working correctly only in Chrome, and in the other browsers I'll get a result of "Showing 0 to 0 records (filtered from 67 total records)" so here it returns true but it filters incorrectly - i.e. it shows 0 results after filtering regardless of what values are in the datepicker inputs.
Ugh! why is my code only working in Google Chrome and not working in other browsers (Safari, IE, FireFox)?? Any help is appreciated, thanks in advance!
I have created a plunker from your script and added some made up html table. I used as much of your code as possible but had to adjust some of your ids.
I'm not sure where along the way i made changes that finally got this working, but I guess its mainly related to your filter variables being not global.
// Date range filter
minDateFilter = "";
maxDateFilter = "";
instead of:
// Date range filter
var minDateFilter = "";
var maxDateFilter = "";
Have a look at this Plunker with the full code which runs perfectly on FF 27.0.1 and find out for yourself.
Update:
Simplified the datepicker initialisition to this:
$("#datepicker_from").datepicker({
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: false,
"onSelect": function(date) {
minDateFilter = new Date(date).getTime();
oTable.fnDraw();
}
}).keyup(function() {
minDateFilter = new Date(this.value).getTime();
oTable.fnDraw();
});
This prevents the double assignement of the widget you have done in:
$('#calender-from').click(function() {
$("#datepicker_min").datepicker("show");
});
and:
$("#datepicker_min").datepicker({
"onSelect": function(date) {
minDateFilter = new Date(date).getTime();
oTable.fnDraw();
}
Now it uses its native function to diplay an icon.
Maybe some browser are picky about this.
Updated Plunker
Here is the script that worked for me.
$.fn.dataTableExt.afnFiltering.push(
function(oSettings, aData, iDataIndex){
var dateStart = parseDateValue($("#dateStart").val());
var dateEnd = parseDateValue($("#dateEnd").val());
var evalDate= parseDateValue(aData[5]);
var evalDate1= parseDateValue(aData[6]);
if ((evalDate >= dateStart && evalDate <= dateEnd)||(evalDate1 >= dateStart && evalDate1 <= dateEnd)) {
return true;
}
else {
return false;
}
});`
After all this time I actually finally found out what causes this issue.
Turns out it is an issue with javascript date time objects being parsed differently in different browsers.
So, in order to make your filters fully cross browser friendly, you just need to use date format in your jQuery UI datepicker that works for all broswers to parse dates from using JS new Date(date_var). But that's easier said than done. What I do is manipulate the date time value before sending it through the custom Datatables filter.
See below for the most recent cross browser implementation I've made. It's overall a better implementation than what is in my question because you don't need to worry as much about the filtering api extension it is handled automatically by the function. See the comments in the code itself for an example where I manipulate the date format to work nicely in Safari's date.parse(dateString) syntax.
$(document).ready( function () {
// define vars
var dTable = $('#transactions'),
date_from = null,
date_to = null,
dateRangeFromSearchBox = $('#date_from_range_search'),
dateRangeToSearchBox = $('#date_to_range_search'),
dateRangeResetButton = $('#date_range_reset_button');
// bootstrap our datatable
dTable.DataTable();
// bootstrap datepickers
$('input.datepicker').datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function (date) {
date_from = new Date( dateRangeFromSearchBox.val() ).getTime();
date_to = new Date( dateRangeToSearchBox.val() ).getTime();
// force change event
dateRangeFromSearchBox.trigger('change');
dateRangeToSearchBox.trigger('change');
// disable further if filtering occured
if (!isNaN(date_from) &&
!isNaN(date_from) &&
dateRangeFromSearchBox.val().length > 0 &&
dateRangeToSearchBox.val().length > 0) {
dateRangeFromSearchBox.prop('disabled', true);
dateRangeToSearchBox.prop('disabled', true);
}
}
});
// date range search
// date from
dateRangeFromSearchBox.change( function () {
if (date_from === "" ||
date_to === "" ||
dateRangeFromSearchBox.val().length === 0 ||
dateRangeToSearchBox.val().length === 0) {
//console.log('reset event from box');
dTable_filterColumnByDateRange (dTable, 1, '', '');
// exit asap if date is invalid
} else if ( isNaN(date_from) || isNaN(date_to) ) {
//console.log('nan event from box')
return;
} else {
//console.log('filter event from box');
// we good? let's filter
dTable_filterColumnByDateRange (dTable, 1, date_from, date_to);
}
});
// date to
dateRangeToSearchBox.change( function () {
if (date_from === "" ||
date_to === "" ||
dateRangeFromSearchBox.val().length === 0 ||
dateRangeToSearchBox.val().length === 0) {
//console.log('reset event to box');
dTable_filterColumnByDateRange (dTable, 1, '', '');
// exit asap if date is invalid
} else if ( isNaN( new Date( dateRangeToSearchBox.val() ).getTime() ) || isNaN(date_from) ) {
//console.log('nan event to box')
return;
} else {
//console.log('filter event from box');
// we good? let's filter
dTable_filterColumnByDateRange (dTable, 1, date_from, date_to);
}
});
//date range reset
dateRangeResetButton.click( function () {
//console.log('reset event');
// this part is crazy
// don't worry I know it is
$('#date_from_range_search').val('').promise().done( function () {
$(this)
.trigger('change')
.prop('disabled', false);
$('#date_to_range_search').val('').promise().done( function () {
$(this)
.trigger('change')
.prop('disabled', false);
});
});
});
});
// and now here is our worker function
// which the above dom ready code is calling:
/**
* Filters a single column based on two date range values
* #param {Object} data_table - jQuery html object instance of the table
* #param {Integer} column_index - DataTables int value of date column to filter
* #param {Integer} date_from - unix time stamp of start date to filter between
* #param {Integer} date_to - unix time stamp of end date to filter between
*/
dTable_filterColumnByDateRange = function (data_table, column_index, date_from, date_to) {
var rowValue_asTimeStamp = null;
data_table
.DataTable()
.column()
.data()
.filter( function (value, index) {
rowValue_asTimeStamp = new Date(value).getTime();
// debug:
//console.log('from', date_from);
//console.log('to', date_to);
//console.log('row', rowValue_asTimeStamp);
//console.log('existing filters?', $.fn.dataTableExt.afnFiltering.length);
if (date_to == null ||
date_to == "" ||
date_from == null ||
date_from == "") {
$.fn.dataTableExt.afnFiltering.pop();
var returnVal = true;
} else {
var returnVal = (rowValue_asTimeStamp >= date_from && rowValue_asTimeStamp <= date_to) ? true : false;
}
})
.draw();
// extend the filter API in the
// most annoying way possible
$.fn.dataTableExt.afnFiltering.push(
function (oSettings, aData, iDataIndex) {
// built in reset?
if (date_to == null ||
date_to == "" ||
date_from == null ||
date_from == "") {
//console.log(aData[column_index]);
return true;
} else {
// debug:
//console.log('arg 1', (new Date(aData[column_index])).getTime());
//console.log('date from', date_from);
//console.log('date to', date_to);
//console.log('truth condition', ((new Date(aData[column_index])).getTime() > date_from && (new Date(aData[column_index])).getTime() < date_to));
/**
* THIS PART MAKES THE FILTER WORK IN SAFARI :)
*/
var parsed = aData[column_index].replace(' ', 'T');
return ((new Date( parsed )).getTime() > date_from && (new Date( parsed )).getTime() < date_to);
}
}
);
};
The above example is intended to work for columns that use a timestamp column value like: <td>2016-08-05 19:14:00</td>

Categories