Javascript scope: Callback function throws "today is not a function" - javascript

I wrote the following code and didn't want to repeat the function (today) twice so I tried writing it within the callback function afterAdd but it didn't work. Why can't it be detected by the callback function?
<script type="text/javascript">
var today = $(document).ready( function() {
var todayDate = new Date();
todayDate.setMinutes(todayDate.getMinutes() - todayDate.getTimezoneOffset());
$('input[name="purchase_date"]').val(todayDate.toISOString().slice(0,10));
});
$(".addform .repeatable").repeatable({
addTrigger: ".add",
deleteTrigger: ".del",
template: "#form_item",
afterAdd: today
});
</script>

First create today as a function. Then call $(document).ready(today), and also use today in your code as per normal:
var today = function() {
var todayDate = new Date();
todayDate.setMinutes(todayDate.getMinutes() - todayDate.getTimezoneOffset());
$('input[name="purchase_date"]').val(todayDate.toISOString().slice(0, 10));
};
$(document).ready(today);
$(".addform .repeatable").repeatable({
addTrigger: ".add",
deleteTrigger: ".del",
template: "#form_item",
afterAdd: today
});

Replace
var today = $(document).ready( function() {
var todayDate = new Date();
todayDate.setMinutes(todayDate.getMinutes() -
todayDate.getTimezoneOffset());
$('input[name="purchase_date"]').val(todayDate.toISOString().slice(0,10));
});
with
var today = function() {
var todayDate = new Date();
todayDate.setMinutes(todayDate.getMinutes() -
todayDate.getTimezoneOffset());
$('input[name="purchase_date"]').val(todayDate.toISOString().slice(0,10));
};
$(document).ready(function() {
today();
});
This will create the function 'today' and run it when the document is ready.

Related

Highlight specific date when datepicker shown

I have this simple datepicker jQuery, and in my application my users can go back to the past, but not future. I want to show the current day base on the date param in the url browser.
Let's say
var url_string = window.location.href;
var url = new URL(url_string);
var dateParam = url.searchParams.get("date"); <<----- current date
I have
$(".clock").click(function() {
$( "#expiryDate" ).datepicker('setDate', date); <<---- Note here
$("#expiryDate").datepicker({
dateFormat: 'yy-mm-dd',
defaultDate: date,
showAnim: "fold",
gotoCurrent: true,
maxDate: 0,
onSelect: function() {
var dateSelected = $(this).datepicker('getDate');
dateSelected = moment(dateSelected).format('YYYY-MM-DD');
// $( "#expiryDate" ).datepicker('setDate', dateSelected);
playSound('forward');
if(dateParam == null) {
var url = document.location.href+"&date="+dateSelected;
}else {
var url = document.location.href;
url = url.replace(dateParam,dateSelected);
}
document.location = url;
}
});
$('#expiryDate').datepicker('show');
});
Even if today is 05/06/2021, users can go back to the past, and see what happened on that day. So when user selected 02/03/2021. I want to highlight that date 02/03/2021. It seems working only if I clicked on my date twice.
Notice only second clicked 3 started to highlight!
How do I make it highlight on first clicked ?
I want to highlight that date 02/03/2021. It seems working only if I clicked on my date twice.
If removed the following code:
var dateSelected = $(this).datepicker('getDate');
dateSelected = moment(dateSelected).format('YYYY-MM-DD');
This can easily be replaces by the onChange function parameter, for more info, take a look at the documentation.
Replaced by:
onSelect: function(dateSelected) {
With that in mind, I've created some sort of [mre] from the code above. This seems to work as expected:
The url_string date is selected on load
On press, the new date is highlighted instantly
var url_string = 'https://example.com?date=2021-05-02'; // DEBUG
var url = new URL(url_string);
var dateParam = url.searchParams.get("date");
console.log('dateParam', dateParam);
$(".clock").click(function() {
$("#expiryDate").datepicker({
dateFormat: 'yy-mm-dd',
defaultDate: dateParam,
showAnim: "fold",
gotoCurrent: true,
maxDate: 0,
onSelect: function(dateSelected) {
console.log('onSelect', dateSelected);
if (dateParam == null) {
var url = document.location.href+"&date="+dateSelected;
} else {
var url = document.location.href;
url = url.replace(dateParam,dateSelected);
}
}
});
$('#expiryDate').datepicker('show');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class='clock'>🕑
<div id='expiryDate' />
</div>
Shooting a bit in the dark for now, since we have low info:
According to your snippets:
var dateParam = url.searchParams.get("date"); <<----- current date
And
$( "#expiryDate" ).datepicker('setDate', date); <<---- Note here
The problem is that you define dateParam while you use date.
It's hard to tell if other code define the date variable, but as a starter, I'd make sure that your date is correctly set...
console.log(date); // Make sure it logs the correct date.
$( "#expiryDate" ).datepicker('setDate', date); <<---- Note here
It is due to the lifecycle of the datepicker. The datepicker will be initialized as
$("#expiryDate").datepicker({});
If you call
$("#expiryDate").datepicker('setDate', date);
Before the datepicker be initialized, that will nothing to do with it at the first time.
At the second time, because of the datepicker was initialized. So, everything works fine. Moreover, once you set the date, it not needs to default date.
Due to reasons of above, the code should be modified as
$(".clock").click(function() {
$("#expiryDate").datepicker({
dateFormat: 'yy-mm-dd',
showAnim: "fold",
gotoCurrent: true,
maxDate: 0,
onSelect: function() {
var dateSelected = $(this).datepicker('getDate');
dateSelected = moment(dateSelected).format('YYYY-MM-DD');
// $( "#expiryDate" ).datepicker('setDate', dateSelected);
playSound('forward');
if(dateParam == null) {
var url = document.location.href+"&date="+dateSelected;
}else {
var url = document.location.href;
url = url.replace(dateParam,dateSelected);
}
document.location = url;
}
});
$("#expiryDate").datepicker('setDate', date); <<---- Note here
$("#expiryDate").datepicker('show');
});

setHours using Pickatime

I am trying to calculate the end time of an appointmnent. I am using pickatime and pickadate by amsul and I combined the the two values to one.
$(document).ready(function(){
var datepicker = $('#date').pickadate({
container: '#outlet',
onSet: function(item) {
if ( 'select' in item ) setTimeout( timepicker.open, 0 )
}
}).pickadate('picker')
var timepicker = $('#time').pickatime({
container: '#outlet',
onRender: function() {
$('<button>back to date</button>').
on('click', function() {
timepicker.close()
datepicker.open()
}).prependTo( this.$root.find('.picker__box') )
},
onSet: function(item) {
if ( 'select' in item ) setTimeout( function() {
$datetime.
off('focus').
val( datepicker.get() + ' ' + timepicker.get() ).
focus().
on('focus', datepicker.open)
}, 0 )
}
}).pickatime('picker')
var $datetime = $('#datetime').
on('focus', datepicker.open).
on('click', function(event) { event.stopPropagation(); datepicker.open() })
What I am tryig to do is adding the duration time to the date and time was picked for the end date. I tried to use getHours and setHours but It is not working.
var sart_time = $('#datetime').val()
I need to do somting like this
var end_time = $('#datetime').val()+duration
I have solved the problem by using momentjs. Here is the code just in case someone came across similar issue.
var booking_start = $('#datetime').val()
var booking_end = moment(booking_time).add(**duration**, 'hours').format('LLL')
duration is a var

JS Countdown not compatible with jQuery 1.10.2

So, my countdown script is for some reason not compatible with my code.
Im trying to make it countdown to a specific time each day, but my web store is limited to only use jquery 1.x with all my other plugins so no other jquery version can be used.
https://jsfiddle.net/nskhbL12/
<script>
window.onload = date;
function ShowTime() {
var now = new Date();
var hrs = 20-now.getHours();
var mins = 60-now.getMinutes();
var secs = 60-now.getSeconds();
timeLeft = "" +hrs+' t : '+mins+' m : '+secs+' s';
$("#countdown").html(timeLeft);
}
var countdown;
function StopTime() {
clearInterval(countdown);
}
setInterval(ShowTime ,1000);
</script>
<span id="date">Order before <span id="countdown"></span> and receive your package tomorrow!</span>
Try with
jQuery(function($) {
setInterval(ShowTime ,1000);
});
Or use something like
$ = jQuery;

jQuery on update event handlers aren't working and I can't figure out why

I'm trying to make a simple calculator for rent arrears, so that as soon as the user types in their values, the "results" section of the table will auto-fill with their results.
At the moment when the user fills in their details, the results section just remains as it was before; however when I de-bug the code, it tells me that there are no errors. I'm pretty sure that the problem is in my event handlers, but I can't work out where/why.
Here is the code:
$(document).ready(function () {
$("#date1").datepicker({
}).on("change", function (e) {
dataBind();
});
$("#date2").datepicker({
}).on("change", function (e) {
dataBind();
});
$(document).on("change", "table input", function () {
dataBind();
});
$("#r1").click(function () {
dataBind();
});
$("#r2").click(function () {
dataBind();
});
$("#r3").click(function () {
dataBind();
});
});
Where date1 and date2 are datepickers, and r1, r2, and r3 are radio buttons.
dataBind is a function which carries out the calculations and updates the results field:
var dataBind = function () {
var config = {
dueDate: new Date($('#date1').val()),
untilDate: new Date($('#date2').val()),
rentAmount: $('#rentAmount').val(),
dueDateResult: $('#date1'),
calcUntilResult: $('#date2')
};
t = new workings(config);
$("#dueDateFirstMissed").html(t.dueDateFirstPaymentResult);
$("#untilDateCalculate").html((t.calculatedUntil));
$("#numberDays").html(t.numberDays.toFixed(0));
$("#numberperiods").html((t.numberPeriods));
$("#amountDue").html("£" + (t.amountDue.toFixed(2)));
$("#dailyRate").html("£" + ((t.dailyRate).toFixed(2)));
};
Here is a link to the fiddle although bear in mind that I haven't finished writing the calculations!
Any help/pointers would be so gratefully appreciated!
Thanks in advance
In your JSFiddle, you have a typo in your getNumberPeriods function, where firsyDate.getMonth() should be firstDate.getMonth(). Rectifying this seems to resolve the issue.
As a sidenote, I would also keep in mind the possibility that someone enter a value that isn't a number in your "Amount of rent due" field. Doing so currently yields NaN in your UI.
Good luck!
There was a syntax error in your variable assigned in below function
function getNumberPeriods() {
var periodLength = getPeriodLength();
var calcDate = (options.untilDate);
var calcYear = calcDate.getFullYear();
var calcMonth = calcDate.getMonth();
var calcDay = calcDate.getDate();
var firstDate = (options.dueDate);
var firstYear = firstDate.getFullYear();
var firstMonth = firstDate.getMonth(); //this was firsyDate.getMonth()
var firstDay = firstDate.getDate();
.....
}
DEMO
UPDATE
You can change your values when you fill all the 3 fields or else you will get NaN in your result and you can do it as below:
var dataBind = function () {
if($("#date1").val()!="" && $("#date2").val()!="" && $('#rentAmount').val()!="")
{ //If all the fields have values then get it done
var config = {
dueDate: new Date($('#date1').val()),
untilDate: new Date($('#date2').val()),
rentAmount: $('#rentAmount').val(),
dueDateResult: $('#date1'),
calcUntilResult: $('#date2')
};
console.log(config);
t = new workings(config);
$("#dueDateFirstMissed").html(t.dueDateFirstPaymentResult);
$("#untilDateCalculate").html((t.calculatedUntil));
$("#numberDays").html(t.numberDays.toFixed(0));
$("#numberperiods").html((t.numberPeriods));
$("#amountDue").html("£" + (t.amountDue.toFixed(2)));
$("#dailyRate").html("£" + ((t.dailyRate).toFixed(2)));
}
};
Note : You haven't given id to your rentAmount textbox at top Just add it too
Updated demo

How to bind three events to the same function in Jquery or jJavascript?

Can anyone explain how can three events can be bind to same function ? i.e. same function should be called when the following events happen.
window unload.
on pressing 'ESC' button.
on clicking 'close' class.
I have written function on clicking '.close' class in following way:
<script>
$(document).ready(function() {
var start = new Date().getTime();
var starttime = new Date(start);
$(".close").click(function () {
jwplayer('mediaplayer').stop();
end = new Date().getTime();
endtime = new Date(end);
$.ajax({
url: "/courses/136",
data: {'timeSpent': endtime - starttime},
});
});
});
</script>
The same thing should happen for window.unload() and on pressing ESC button. Is there any Jquery method for this.
Create a function that is responsible for handling the events and then you just have to pass that function to every event you want to execute it.
<script>
$(document).ready(function() {
var start = new Date().getTime();
var starttime = new Date(start);
var eventHandler = function (event) {
jwplayer('mediaplayer').stop();
end = new Date().getTime();
endtime = new Date(end);
$.ajax({
url: "/courses/136",
data: {'timeSpent': endtime - starttime},
});
};
$(".close").click(eventHandler);
$(window).on("unload", eventHandler);
$(document).on("keydown", function(e) {
if (e.which == 27) {
eventHandler(e);
}
});
});
</script>
You just define the function:
function handler() {
jwplayer('mediaplayer').stop();
end = new Date().getTime();
endtime = new Date(end);
$.ajax({
url: "/courses/136",
data: {'timeSpent': endtime - starttime},
});
}
...and bind it three times; for the ESC key part you probably want a wrapper:
$(".close").click(handler);
$(window).on("unload", handler);
$(document).on("keydown", function(e) { // Or whatever element is relevant
if (e.which == 27) {
handler.call(this, e); // With the above, just `handler();` would work too
}
});
The functions that you pass to jQuery methods like .click() don't have to be anonymous. You can refer to a function by name. So:
function yourFunction() {
// do your jwplayer and ajax thing here
}
$(window).on("unload", yourFunction);
$(".close").click(yourFunction);
$(document).on("keyup", function(e) {
if (e.which == 27)
yourFunction();
});

Categories

Resources