I want to highlight overdue task when refresh page and when click on add task button such as the code below:
$(document).ready(function(){
$('.add-task').on('click',function(){
$('.task-date').each(function(){
var a = new Date().dateFormat('dd/mm/yy').getTime();
var b = formatDate(b,'dd/mm/yy').getTime();
var task = new Date($('.task-date')).getTime();
if(task < b) {
return $('todo-task').addClass('overdue');
}
});
});
});
I tried some other ways but still not working so please check JSFiddle here and source site here and help me. Thank you.
var generateElement = function(params){
var parent = $(codes[params.code]),
wrapper;
if (!parent) {
return;
}
var curDate=new Date();
var overDueClass="";
if(params.date<curDate){ // Check the current date is less than to-do date here
overDueClass=" overdue";
}
wrapper = $("<div />", {
"class" : defaults.todoTask+overDueClass,
"id" : defaults.taskId + params.id,
"data" : params.id
}).appendTo(parent);
.....................
...............
}
For solve your task no need to create new functions. You may just apply the logic in generateElement function in your todo.js file.
var d = new Date();
var date = d.getDate() + "/" + d.getMonth()+1 + "/" + d.getFullYear();
var overDueClass= "";
// Add Task
var generateElement = function(params){
var parent = $(codes[params.code]),
wrapper;
if (!parent) {
return;
}
// Check the current date is less than to-do date.
if(params.date < date) {
overDueClass= "overdue";
} else {
overDueClass="";
};
wrapper = $("<div />", {
"class" : defaults.todoTask+" "+overDueClass,
"id" : defaults.taskId + params.id,
"data" : params.id
}).appendTo(parent);
Related
How can I auto-complete an input date using JavaScript?
Like for example I input 5/2 it'll automatically be 20190502
function dateManagement(dateValue) {
var inputs = dateValue.split('/');
var month = (inputs[0].length == 1) ? '0' + inputs[0] : inputs[0];
var date = (inputs[1].length == 1) ? '0' + inputs[1] : inputs[1];
return new Date().getFullYear() + '' + month + '' + date;
}
function setupLevel1ItemDateManagementEditFunction(dateValue){
addLoadEvent(initLevel1ItemDateManagementEditFunction(dateValue));
}
function initLevel1ItemDateManagementEditFunction(dateValue){
return function(){
var dateVal = disp.getElement(dateValue);
addEventHandler(dateVal ,"onkeydown", function(e){
if(e.keyCode == KEY_ENTER){
var input = disp.get(dateValue);
var edited = "";
try{
edited = dateManagement(dateValue);
} catch(e){
console.log(e);
}
if(edited != "" && edited !=null){
disp.set(dateValue, edited);
}
}
return true;
});
return true;
};
}
i have tried reading a lot of threads and forums and i still dont get it.
i am completely new to coding so pls bear with me.
This is a very bad approach to set a date. But if you really needs to do this, you can use following function.
function getFullDate(yourInputText) {
var inputs = yourInputText.split('/');
var month = (inputs[0].length == 1) ? '0' + inputs[0] : inputs[0];
var date = (inputs[1].length == 1) ? '0' + inputs[1] : inputs[1];
return new Date().getFullYear() + '/' + month + '/' + date;
}
console.log(getFullDate('5/2')); //output: '2019/05/02'
Note:
new Date().getFullYear() will give you the current year.
I'm trying to prevent polluting the global space with a bunch of variables, and since I can't use let yet, I have to make closures. So I have this basic webpage with a bootstrap accordion, each card hiding different examples. In one I have a form that asks in a <select> what your position is. OnChange it will grab the eventData object, call spillObject() (the closure method), and populate another accordion card with its contents. It works, but problem is, I can't seem to make it work as a simple closure. Nothing seems to happen, and since you can't debug a closure, other than making it spit out console.logs() everywhere, I can't find out what's wrong with it.
Here's the code:
$(function() {
$("#position").change( /*(*/ function(eventData) {
var div = $('#explodedObject');
div.html('');
var result = spillObject('#explodedObject', eventData, '');
/*};*/
div.append(result);
} /*)()*/ );
var spillObject = (function(dataParent, obj, heirarchy) {
var heirArr = heirarchy == '' ? [] : heirarchy.split('_');
heirArr.push(1);
var teir = heirArr.length - 1;
var id = "#collapse" + heirArr.join('');
var headerID = 'header' + heirArr.join('');
var card = document.createElement('div');
card.classList.add('card');
var cardHeader = document.createElement('div');
cardHeader.classList.add('card-header');
cardHeader.id = headerID;
var h5 = document.createElement('h5');
h5.classList.add('mb-0');
var button = document.createElement('button');
button.classList.add('btn', 'btn-link');
button.setAttribute('data-toggle', 'collapse');
button.setAttribute('data-target', id);
var cardBody = document.createElement('div');
cardBody.classList.add('card-body');
var collapse = document.createElement('div');
collapse.id = id.substr(1, id.length - 1);
collapse.classList.add('collapse');
collapse.setAttribute('data-parent', dataParent);
var dl = document.createElement('dl');
dl.id = '#' + heirArr.join('');
var dt;
var dd;
var x;
return function() {
for (x in obj) {
dt = document.createElement('dt');
dd = document.createElement('dd');
dt.innerHTML = x;
if (typeof obj[x] == 'object' && heirArr.length < 3) {
heirArr[teir]++;
innerObj = spillObject(dl.id, obj[x], heirArr.join('_'));
dd.appendChild(innerObj);
} else {
dd.innerHTML = obj[x];
}
dl.append(dt);
dl.append(dd);
}
heirArr.pop();
heirArr[heirArr.length - 1] = parseInt(heirArr[heirArr.length - 1]);
heirArr[heirArr.length - 1]--;
collapse.appendChild(cardBody);
button.innerHTML = 'card ' + heirArr.join('.');
h5.appendChild(button);
cardHeader.appendChild(h5);
card.appendChild(cardHeader);
card.appendChild(collapse);
cardBody.appendChild(dl);
return card;
};
});
})();
More basically, I'm following this template:
var method = (function(param){
var var1 = 'default value';
return function(){
var1 = 'something else';
};
})();
Should I have used this one instead, and if so would it hide the variables?
var method2 = function(param) {
return function() {
var var1 = 'default value';
};
};
It's because the result of spillObject is a function, you must then also call that function. Here's a simplified version of what you are doing.
var spillObject = (function(dataParent, obj, heirarchy) {
console.log('first function')
return function() {
console.log('second function')
};
});
var result = spillObject()
console.log(result)
result()
I seem to be having quite a simple error that I cannot seem to figure out. I have two functions. One that allows for a timed iteration through an array (slow iteration) and another that just combines the items in the array into a sentence (testfunction). I want these two functions to be called in a while loop so that the while loop will continually run between times in the day (this is the Now_time variable).
If i run the code without the while loop it runs correctly. As soon as I introduce the while loop it only iterates the first element and not continuously through the array using the functions.
Any suggestions?
//Sample array
var data = [
{Name:"Cape Town",City_Type:"Seaside"}
,
{Name:"Johannesburg",City_Type:"Inland"}
,
{Name:"Durban",City_Type:"Seaside"}
,
{Name:"Bloemfontein",City_Type:"Inland"}
];
// Slowly iterates through a given array
function slowArrayIterate(array, iterateFunc, start, speed) {
iterateFunc(array[start], start, array);
if (typeof array[start + 1] !== 'undefined') {
setTimeout(function() {
slowArrayIterate(array, iterateFunc, start + 1, speed, done);
}, speed);
} else {
done();
}
}
// Forms the sentence from the elements in the array
function testfunction(a,b){
var complete = a +" is a " + b +" city.";
console.log(complete);
}
// Gets the time of the day
var myDate = new Date(Date.now());
var time_now = myDate.toString().substring(16,24);
var here = time_now;
var there = time_now;
var everywhere = time_now;
var now = here.substring(0,2)+ there.substring(3,5) + here.substring(6,8);
var Now_time = parseFloat(now);
while (Now_time >= 73000 || Now_time <=170000) {
console.log("working");
// Calls the fucntion to slowly iterate
slowArrayIterate(data, function(arrayItem) {
console.log(arrayItem.Name);
console.log(arrayItem.City_Type);
// Calls the fucntion to form a sentence on the console log
testfunction(arrayItem.Name , arrayItem.City_Type);
}, 0, 1000);
// refreshes the time to see if it should still be running
myDate = new Date(Date.now());
var time_now = myDate.toString().substring(16,24);
var here = time_now;
var there = time_now;
var everywhere = time_now;
var now = here.substring(0,2)+ there.substring(3,5) + here.substring(6,8);
var Now_time = parseFloat(now);
console.log(Now_time);
}
There is error in the "done" function you are passing - include it inside the function call as :-
var data = [
{Name:"Cape Town",City_Type:"Seaside"}
,
{Name:"Johannesburg",City_Type:"Inland"}
,
{Name:"Durban",City_Type:"Seaside"}
,
{Name:"Bloemfontein",City_Type:"Inland"}
];
// Slowly iterates through a given array
function slowArrayIterate(array, iterateFunc, start, speed, done) {
iterateFunc(array[start], start, array);
if (typeof array[start + 1] !== 'undefined') {
setTimeout(function() {
slowArrayIterate(array, iterateFunc, start + 1, speed, done);
}, speed);
} else {
done();
}
}
// Forms the sentence from the elements in the array
function testfunction(a,b){
var complete = a +" is a " + b +" city.";
console.log(complete);
}
// Gets the time of the day
var myDate = new Date(Date.now());
var time_now = myDate.toString().substring(16,24);
var here = time_now;
var there = time_now;
var everywhere = time_now;
var now = here.substring(0,2)+ there.substring(3,5) + here.substring(6,8);
var Now_time = parseFloat(now);
while (Now_time >= 73000 || Now_time <=170000) {
console.log("working");
// Calls the fucntion to slowly iterate
slowArrayIterate(data, function(arrayItem) {
console.log(arrayItem.Name);
console.log(arrayItem.City_Type);
// Calls the fucntion to form a sentence on the console log
testfunction(arrayItem.Name , arrayItem.City_Type);
}, 0, 1000, function() { //problem was here
// stuff to do when finished (not important for now)
console.log("Done");
});
// refreshes the time to see if it should still be running
myDate = new Date(Date.now());
var time_now = myDate.toString().substring(16,24);
var here = time_now;
var there = time_now;
var everywhere = time_now;
var now = here.substring(0,2)+ there.substring(3,5) + here.substring(6,8);
var Now_time = parseFloat(now);
console.log(Now_time);
}
I have a search page where you can search books and apply several filters. On allpying filter I am sending the request in the URL to server. I have implemented that using the following javascript ->
$(document).ready(function(){
var base_url = 'https://'+window.location.hostname;
var url = base_url+'/books/search/';
var next_url = base_url+'/books/search/next/';
var filter_url = base_url+'/books/search/filter/';
var search_input = $('.search-bar input');
var bookSeach = {
searchQueryAsString : function(el){
var id = $(el).attr('id');
var id = id.substr(id.lastIndexOf('_')+1)
var filter_type = $(el).closest('ul.p-search-var-items').attr('filter-type')
var name = $(el).val();
$('#'+filter_type+'_id').val(id)
$('#'+filter_type+'_name').val(name)
return this.buildSearchQuery()
},
searchQueryAsArray : function(el){
el.find('input:checkbox:checked').each(function(){
var filter=$(this).closest('.p-search-var-items').attr('filter-type')
var id = $(this).attr('id')
var name = $(this).val()
id = id.substr(id.lastIndexOf('_')+1)
var value = $('#'+filter+'_id').val()!='' ?$('#'+filter+'_id').val()+','+id : id
$('#'+filter+'_id').val(value)
var nvalue = $('#'+filter+'_name').val()!='' ?$('#'+filter+'_name').val()+','+name : name
$('#'+filter+'_name').val(nvalue)
})
return this.buildSearchQuery()
},
buildSearchQuery : function(){
var self = this;
var query_url = base_url+'/books/search/';
$('input.filter_value').each(function(){
var el = $(this);
if(el.val()!=''){
value = $.trim(el.val())
query_url = self.updateQueryStringParameter(query_url,el.attr('id'),value)
next_url = self.updateQueryStringParameter(next_url,el.attr('id'),value)
filter_url = self.updateQueryStringParameter(filter_url,el.attr('id'),value)
}
})
return {'url':query_url,'next_url':next_url,'filter_url':filter_url};
},
updateQueryStringParameter : function(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, '$1' + key + "=" + value + '$2');
}
else {
return uri + separator + key + "=" + value;
}
},
filterText : function (elem) {
var value = elem.val().toLowerCase();
var filter = elem.attr('data-filter')
$(".p-search-var-items[filter-type='"+filter+"'] > li").each(function() {
if ($(this).text().toLowerCase().search(value) > -1) {
$(this).show();
}
else {
$(this).hide();
}
});
},
loadBooksOnScroll : function(count){
var ajax_url = bookSeach.buildSearchQuery()
if($('#dropdownMenu1').attr('data-filter-applied')!=''){
ajax_url = ajax_url['filter_url']
data = {'index':count,'type':$('#dropdownMenu1').attr('data-filter-applied')}
}else{
ajax_url = ajax_url['next_url']
data = {'index':count}
}
this.ajaxHandler(ajax_url,'GET',data,this.renderBookList)
},
loadBooksOnSort : function(type){
var ajax_url = bookSeach.buildSearchQuery()
ajax_url = ajax_url['filter_url']
this.ajaxHandler(ajax_url,'GET',{'index':0,'type':type},function(response){
$('.p-result').html('')
bookSeach.renderBookList(response)
})
},
ajaxHandler : function(url,method,data,callback){
$.ajax({
'url':url,
'type':method,
'data':data,
'success':function(response){
if(response){
callback(response)
}
}
})
},
filterContentByKeyWord: function(key,type){
var keyword = {}
keyword[type+'_key']=key
var ajax_url = base_url+'/'+type+'s/search/';
this.ajaxHandler(ajax_url,'GET',keyword,function(result){
bookSeach.renderFilterContent(result,type)
})
},
renderFilterContent: function(results,type){
$('.'+type+'-results').html('')
var template =_.template($('#'+type+'_template').html())
var id = this.getUrlParameter(type+'_id')
console.log(id, results,id)
$('.'+type+'-results').append(template({'results':results,'id':id}))
},
renderBookList : function(books){
var template =_.template($('#book_detail').html())
$('.p-result').append(template({'books':books}))
},
removeParameter : function(url, parameter){
var urlparts= url.split('?');
if (urlparts.length>=2)
{
var urlBase=urlparts.shift(); //get first part, and remove from array
var queryString=urlparts.join("?"); //join it back up
var prefix = encodeURIComponent(parameter)+'=';
var pars = queryString.split(/[&;]/g);
for (var i= pars.length; i-->0;)
if (pars[i].lastIndexOf(prefix, 0)!==-1) //idiom for string.startsWith
pars.splice(i, 1);
url = urlBase+'?'+pars.join('&');
}
return url;
},
getUrlParameter : function(sParam){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
};
// Search within filters by keyword - START
//Delay function to prevent calling the function on every key press
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
//On keyup for search within filters
$('.p-search-cat-box').on('keyup',function(){
var self = this
delay(function(){
var filter = $(self).attr('data-filter');
if(filter=='author' || filter=='publisher' || filter=='seller' || filter=='institute'){
$('#'+filter+'_key').val($(self).val())
bookSeach.filterContentByKeyWord($(self).val(),filter)
}else{
bookSeach.filterText($(self))
}
}, 600 )
});
// Search within filters by keyword - END
//Filters on change event - START
// For category and sub category
$('.p-search-var-items input:radio').on('change',function(){
var redirect_url = bookSeach.searchQueryAsString($(this))
window.location.href = redirect_url['url'];
})
// For Authors, Publishers and Binding
$(document).on('change','.p-search-var-items input:checkbox',function(){
elem = $(this)
el = elem.closest('.p-search-var-items')
$('#'+el.attr('filter-type')+'_id').val('')
$('#'+el.attr('filter-type')+'_name').val('')
var redirect_url = bookSeach.searchQueryAsArray(elem.closest('.p-search-cat-list'))
window.location.href = redirect_url['url'];
})
//Filters on change event - END
// Filters - collapse up and down - START
$('.filter-container .p-sub-cat i').on('click',function(){
if($(this).hasClass('fa-minus')){
$(this).closest('.filter-container').find('.p-search-cat').hide("slide",{direction:'up'},500)
$(this).removeClass('fa-minus')
$(this).addClass('fa-plus')
}else{
$(this).closest('.filter-container').find('.p-search-cat').show("slide",{direction:'up'},500)
$(this).removeClass('fa-plus')
$(this).addClass('fa-minus')
}
})
// Filters - collapse up and down - END
//Search box Header - START
$('#search_books').on('click',function(){
var redirect_url = bookSeach.buildSearchQuery()
window.location.href = redirect_url['url'];
})
$("#query").keyup(function(event){
if(event.keyCode == 13){
$("#search_books").trigger('click');
}
});
//Search box Header - END
//Applied FIlters - remove option
$('.p-filter-title img').on('click',function(){
var param = $(this).attr('data-applied-filter')
if(param=='author' || param=='publisher' || param=='seller' || param=='institute' || param=='binding' ){
var id = $(this).attr('data-filter-id')
$('#'+param+'_'+id).removeAttr('checked')
$('#'+param+'_'+id).trigger('change')
}else{
var paramname = param.substr(0,param.lastIndexOf('_')+1)
url = bookSeach.removeParameter(window.location.href,paramname+'name')
redirect_url = bookSeach.removeParameter(url,param)
window.location.href = redirect_url
}
})
//Infinite Scroll - Book Results - START
if(location.href.indexOf('books/search/')>0){
var count =10;
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
bookSeach.loadBooksOnScroll(count);
count+=10;
}
});
}
//Infinite Scroll - Book Results - END
//Filters in Responsive Layout - START
$('.apply').on('click',function(){
$('.mobile-filters ul.p-search-var-items span.m_apply_filter').each(function(){
if($(this).attr('data-is-selected')=='true'){
var id = $(this).attr('data-id')
var type = $(this).attr('data-type')
var value = $('#m_'+type+'_id').val()!=''? $('#m_'+type+'_id').val()+','+id : id
$('#m_'+type+'_id').val(value)
}
})
$('.m_filter').each(function(){
var param = $(this).attr('id');
param = param.substr(param.indexOf('m_')+2)
value = $.trim($(this).val())
redirect_url = bookSeach.updateQueryStringParameter(url,param,value)
})
window.location.href = redirect_url
})
$('.m_apply_filter').on('click',function(){
if($(this).attr('data-is-selected')=='false'){
$(this).closest('li').addClass('p-search-var-items-active')
$(this).attr('data-is-selected','true')
}else{
$(this).closest('li').removeClass('p-search-var-items-active')
$(this).attr('data-is-selected','false')
}
})
//Filters in Responsive Layout - END
$('.back-to-top').on('click', function(){
$(window).scrollTop(0 )
})
$(window).on('scroll', function(){
if($(window).scrollTop()>1200){
$('.back-to-top').removeClass('hide')
}else{
$('.back-to-top').addClass('hide')
}
})
$('.presentation a').on('click', function(e){
e.preventDefault();
var type= $(this).data('type')
bookSeach.loadBooksOnSort(type)
$('#dropdownMenu1 .sort_filter').text('Sort by :'+type)
$('#dropdownMenu1').attr('data-filter-applied',type)
})
}
})
})
What it does is when you select a filters it changes the url makes a server call and displays the data accordingly.
It also implements infinite scroll on scrolling down it loads 10 more results.
I want to implement the entire thing using Angular2 with typescript. Can someone please suggest me how to implement my js code using typescritp and Angular2. I am new to angular so I am having some problem in implementing the same.
Thank you.
This is more of an advise than answer. You should avoid using jQuery in Angular. The reason being jQuery modifies the DOM directly and Angular modifies the DOM via an abstraction. You'll run into a lot of trouble doing so.
I couldn't be stuff reading through all that, it's a big mess and doesn't look like you're doing it the proper way anyways and your methods are big and fat and noisy.
If your aim is after scrolling to a certain length then query and display more data then you can try something like:
#HostListener('window:scroll', []) onWindowScroll($event: any) {
// your logic...
}
Then in your template use *ngIfetc...
I'm too very new to angular 2 but this tutorial helped me a lot:
https://www.pluralsight.com/courses/angular-2-getting-started
further to implement infinite scroll use:
https://www.npmjs.com/package/angular2-infinite-scroll.
hope this helps :)
I'm pretty new to js and having a hard time figuring out the best way to generate a custom url depending on what links are selected. You can view what I have done here. http://jsfiddle.net/1fz50z1y/26/ I will also paste my info here.
var products = [];
var quantity = [];
qstring = '';
$('input.product-radio, select.products-howmany').change(function() {
var $this = $(this)
var $product = $(this).closest('.product-options-left');
var $radio = $product.find('input.product-radio');
var $select = $product.find('select.products-howmany')
var qid = $select.val();
var pid = $radio.val();
currentStatus = $radio.prop('checked'),
theString = '';
qString = '';
pString = '';
if (currentStatus) {
products.push(pid);
quantity.push(qid);
if ($product.find('div.quantity').removeClass('q-hidden')) {
//code
}
} else {
products.splice(products.indexOf(pid), 1);
quantity.splice(quantity.indexOf(qid), 1);
$product.find('div.quantity').addClass('q-hidden');
}
if ((products.length > -1) || (quantity.length > -1)) {
if ((products.length === 0) || (quantity.length === 0)) {
console.log("Q Length: " + quantity.length);
pString += products[0];
qString += quantity[0];
console.log("qString = " + quantity);
} else {
pString = products.join('-p');
qString = quantity.join('_q');
if (quantity.length > 1) {
qString = quantity.splice(quantity.indexOf(qid), 1);
pString = products.splice(products.indexOf(pid), 1);
}
console.log("+ Q Length: " + quantity.length);
console.log("ADDING " + "p" + pString + "_q" + qString);
}
if ((qString == 'undefined') || (pString == 'undefined')) {
$('a.options-cart').prop("href", "#");
} else {
//$('a.options-cart').prop("href", "/cart/add/p" + theString + "_q" + qstring + "?destination=/cart");
//$('a.options-cart').prop("href", "/cart/add/p" + theString + "?destination=/cart");
$('a.options-cart').prop("href", "/cart/add/p" + pString + "_q" + qString + "?destination=/cart");
}
}
});
$('a.options-cart').click(function() {
alert(qstring);
var $this = $(this);
href = $this.attr('href');
if (href == '#') {
alert("You must select a product.");
return false;
}
});
When you click on the add link icon it displays a drop down where you can select the quantity. So changing the quantity should also update the link and how it is created. I am trying to figure out how to create the link so the end result looks like so.
cart/add/p123_q1?destination=/cart this is how it would look with a single item. Where p = the product ID and q = the quantity. Unclicking the add to cart should remove those items and changing the drop down should update the quantity. If there is more than one item it should append to the link like so. cart/add/p123_q1-p234_q2-p232_q4?destination=/cart and then unclicking or changing quantity on any of those items should reflect the change in the link. I am not sure if I am going about this all wrong but I have been trying forever and many different routes to go about trying to achieve this effect. If anyone could please help me figure this out I would be greatly appreciated!
I was able to get this to work properly using this piece of code. Hope this maybe helps someone.
$('input.product-radio, select.products-howmany').change(function () {
var $product = $(this).closest('.product-options-left');
var $radio = $product.find('input.product-radio');
var $select = $product.find('select.products-howmany')
$product.find('div.quantity').toggleClass('q-hidden', !$radio.prop('checked'));
$product.find('label.quantity').toggleClass('q-hidden', !$radio.prop('checked'));
var string = $('.product-radio')
.filter(':checked')
.map(function(){
return $(this)
.closest('.product-options-left')
.find('.products-howmany')
.val();
})
.get()
.join('-');
$('a.options-cart').prop("href", "/cart/add/" + string + "?destination=/cart");
});
$('a.options-cart').click(function() {
alert(qstring);
var $this = $(this);
href = $this.attr('href');
if (href == '#') {
alert("You must select a product.");
return false;
}
});