JQuery On event after element is changed via Javascript - javascript

I am trying to create a jquery plugin to do custom validation.
I have a jqueryUI date picker that enters a date into an input field.
I am trying to attach an on change event to the input field that gets populated by the date picker but it isn't firing. I guess because it isn't being changed by the user, it is being updated by JavaScript/jqueryUI.
My question is how can I attach an on change event to a field that is updated via JavaScript and not by the user?
my plugin code:
;(function ($, window) {
var validateStuff = function(element){
$(element).on('change', function(event){
console.log( "Handler for .on() called." );
});
};
$.fn.validate = function(options){
return this.each(function(){
var elem = $( this );
validateStuff(elem);
});
};
})(jQuery);
UPDATE:
datepicker code
$('.day-picker').datepicker({
inline: true,
showOtherMonths: true,
dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
onSelect: function (dateText, inst) {
var startDate = new Date(dateText);
var selDay = startDate.getDate();
var selMonth = startDate.getMonth() + 1;
var selYear = startDate.getFullYear();
var fieldElement = $(this).siblings(".date-field");
var selDay = selDay < 10 ? "0" + selDay : selDay;
var selMonth = selMonth < 10 ? "0" + selMonth : selMonth;
$(fieldElement).val(selDay + "-" + selMonth + "-" + selYear);
}
});

When you change the value of the input element, you can trigger the change event:
$(fieldElement).val(selDay + "-" + selMonth + "-" + selYear).change();
Which can also be written as
$(fieldElement).val(selDay + "-" + selMonth + "-" + selYear).trigger('change');
Note: Event handler methods like change() will simply trigger the event if no parameters are passed.

Related

How to update a Jquery calendar with a JS variable

I am trying to implement this jQuery Calendar into my website. I've got the calendar running, and everything works.
I want to be able to alter the date in the calendar when a user pushes one of four buttons:
1 hour
Tomorrow
1 week
2 weeks
When a user pushes a button I would like the calendar to change the date accordingly. The calendar has the option called startDate that I can use for the purpose - but I can't seem to trigger it.
The content of val = f.x. 2020-03-07 10:02
$.datetimepicker.setLocale('da');
$('#datetimepicker').datetimepicker({
dayOfWeekStart: 1,
lang: 'da',
inline: true,
scrollMonth: false,
timepicker: false,
startDate: new Date(document.getElementById('timeForAlert').value),
onSelectDate: function() {
userHasChosen();
},
onSelectTime: function() {
userHasChosen();
}
});
$('#datetimepicker4').datetimepicker({
format: 'Y-d-m'
});
$('.some_class').datetimepicker();
function makeReadable(val) {
var mydate = new Date(val);
var hour = document.getElementById('hour').value;
var minute = document.getElementById('minutes').value;
var str = mydate.getFullYear() + '-' + ("0" + (mydate.getMonth() + 1)).slice(-2) + '-' + ("0" + mydate.getDate()).slice(-2) + ' ' + hour + ':' + minute + ':00';
return str;
}
function oneday(val) {
document.getElementById('datetimepicker').value = val;
document.getElementById('timeForAlert').value = makeReadable(val);
$.datetimepicker();
stopReload();
}
Found the solution asking in another forum.
The documentation for this script is terrible !
Here is what we found:
$(function() {
$('#dt').datetimepicker({
dayOfWeekStart: 1,
lang: 'da',
inline: true,
scrollMonth: false,
timepicker: false,
startDate: new Date()
});
});
$('#btn').click(function() {
$('#dt').datetimepicker({
value: new Date('2020-01-01T00:00:00Z')
});
});
Run this from a button with id = btn and you're set

How to get date in specific format

I want to have the dateformat in this format: 2015-08-04T00:00:00Z.
so first year, month, day.
beforeShowDay: function (date) {
var dt = $.datepicker.formatDate('yy-mm-dd', date, "getDate")
return [$('#form_one3 > option:gt(0)[value="' + dt + 'T00:00:00Z"]').length != 0];
},
onSelect: function (dateText, inst) {
var dt = $.datepicker.formatDate('yy-mm-dd', dateText, "getDate")
alert(dt);
var hallo = $("#form_inp1").val() + 'T00:00:00Z';
alert(dateText);
alert(hallo);
//$("#form_inp1").datepicker("getDate");
//alert($("#form_inp1").formatDate('yy-mm-dd', dateText, "getDate")
},
But If I do an alert(dateText) I see the format as: 4-8-2015 and it has to be: 2015-08-04.
Thank you
If I try it like this:
onSelect: function (dateText, inst) {
dateText = dateText.split("-");
dateText = new Date('' + dateText[2] + '-' + dateText[1] + '-' + dateText[0] + '');
alert(dateText);
}
I get invalid date
So this var hallo = $("#form_inp1").val() + 'T00:00:00Z';
returns: 4-8-2015T00:00:00Z . But it has to be:2015-08-04T00:00:00Z.
Thank you
Quick fix is to change the date format using plain Javascript. This can be achieved by following script.
dt= dt.split("-");
dt = new Date('' + dt[2] + '-' + dt[1] + '-' + dt[0] + '');
to add zero in case the day, month and year is below 10, use following method.
function AddTrailingZero(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
Let me know if you have any question related to the code snippet above.

jQuery: beforeShowDay date format issue

I'm using the jQuery ui datepicker in combination with the isotope plugin and filter feature to filter out divs by date. For this filter feature to work the date has been converted to a string and stipped out all the zeros, e.g. 20/08/2013 would read as 2082013. I'm also using the beforeShowDay feature to highlight the relevant dates in the date picker, this is where the problem lies, in my example below as I'm using this date format 1782013 1882013 1982013 is also styling 01/08/2013 etc (as you can see in the fiddle).
jsFiddle: http://jsfiddle.net/neal_fletcher/jPzK2/1/
jQuery:
var $container = $('#block-wrap');
var $blocks = $("div.blocks", "#block-wrap");
$(function () {
var blocks = $('#block-wrap .blocks')
$('#datepicker').datepicker({
inline: true,
//nextText: '→',
//prevText: '←',
showOtherMonths: true,
//dateFormat: 'dd MM yy',
dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
//showOn: "button",
//buttonImage: "img/calendar-blue.png",
//buttonImageOnly: true,
onSelect: function (dateText, inst) {
var date = new Date(dateText);
var dateValue = date.getDate().toString() + (date.getMonth() + 1).toString() + date.getFullYear().toString();
$container.isotope({
filter: '[data-value~="' + dateValue + '"]'
});
},
beforeShowDay: function(date){
var target = date.getDate().toString() + (date.getMonth() + 1).toString() + date.getFullYear().toString();
var contains = blocks.filter('[data-value*="' + target + '"]').length > 0;
return [true, contains ? 'special' : '', '']
}
});
});
$container.imagesLoaded(function () {
$container.isotope({
itemSelector: '.blocks',
animationEngine: 'css',
masonry: {
columnWidth: 5
}
});
});
var prepareData = function (howLong) {
var mode = howLong,
date = new Date(),
days = 0,
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear(),
duration = [],
durationReady = [];
if (mode === "week") {
days = 7;
} else if (mode === "month") {
days = 30;
}
for (i = 0; i < days; i++) {
// for each day create date objects in an array
duration[i] = new Date(y, m, d + i);
// convert objects into strings
// fe. 25th of May becomes '2552013'
durationReady[i] = duration[i].getDate().toString() + (duration[i].getMonth() + 1).toString() + duration[i].getFullYear().toString();
// 1. select all items which contain given date
var $applyMarkers = $('.blocks[data-value~="' + durationReady[i] + '"]')
.each(function (index, element) {
var thisElem = $(element),
thisElemAttr = thisElem.attr('data-value');
// 2. for each item which does not contain a marker yet, apply one
if (thisElemAttr.indexOf(mode.substring(0, 1)) === -1) {
thisElem.attr('data-value', (thisElemAttr += ' ' + mode));
}
});
}
};
prepareData("week");
prepareData("month");
$("#today").on("click", function () {
var date = new Date();
var dateValue = date.getDate().toString() + (date.getMonth() + 1).toString() + date.getFullYear().toString();
$('#datepicker').datepicker('setDate', date);
$container.isotope({
filter: '[data-value~="' + dateValue + '"]'
});
});
$("#week").on("click", function () {
$container.isotope({
filter: '[data-value ~="week"]'
});
});
$("#month").on("click", function () {
$container.isotope({
filter: '[data-value ~="month"]'
});
});
As you can see, all the dates in the data-value are successfully styled in the date picker, but due to the date format it's also styling the 1st — 9th August too. Is there anyway for both the filter function and beforeShowDay function to work without this problem?
& yes, changing the date format to e.g. 21082013 does solve the beforeShowDay styling issue, but breaks the filter function, they both need to work. Any suggestions would be greatly appreciated!
You are using * selector in your beforeShowDay function
('[data-value*="' + target + '"]')
That is why 1st August got styled - because it matches "2182013" value.
Change it to a words selector ~
('[data-value~="' + target + '"]')

How to set datetimepicker to localtime when posting form

I have a problem when i am posting a editform with a datetime value in it. I have a script that sets the localdatetime with getTimeZonOffset. The first time when i want the utc time from the database to be displayed in localtime it works. The problem is when i want to edit the form with a datetimepicker. The new value gets stored in the database and every time the user hits the submit button it adds the localtime again.
How can i do to avoid this?
$(function () {
// Determine timezone offset in milliseconds
var d = new Date();
var offsetms = d.getTimezoneOffset() * 60 * 1000;
$('.UTCTime input').each(function () {
try
{
var text = $(this).val();
var n = new Date(text);
n = new Date(n.valueOf() - offsetms);
var curr_date = n.getDate();
var curr_month = n.getMonth() + 1; //Months are zero based
var curr_year = n.getFullYear();
var curr_hour = n.getHours();
var curr_minutes = n.getMinutes();
$(this).val(curr_year + "/" + curr_month + "/" + curr_date + " " + curr_hour + ":" + curr_minutes);
}
catch (ex) {
console.warn("Error converting time", ex);
}
});
});
$(function () {
$(".datetimepicker input").datetimepicker({
dateFormat: "yy/mm/dd",
showTime: true,
});
});
<div class="span3 value UTCTime datetimepicker">
It looks like your script will override any value already saved when you edit it
You need to add some kind of check when setting the datetime value so you dont override it
if( !$(this).val() ) {
$(this).val(curr_year + "/" + curr_month + "/" + curr_date + " " + curr_hour + ":" + curr_minutes);
}
You might have to change the if-condition if you have some other default value
Make unique index in your database for userid and timezone, that means that the current time zone can not be re entered again for the same user it can be updated.
If you have mysql db then use insert into table on duplicate key update....
Hope this will give you the correct idea.

Unexpected Identifier Syntax Error in Javascript

I get an Unxepected Identifier editor with the following code. I've been troubleshooting it all day, and nothing. Hoping a fresh pair of eyes can spot my error. I'm trying to use jQuery UI to set up a date-picker and then get and manipulate the date. Changing the date on the picker should change an image on the page associated with that date via ajax.
$(document).ready(function(){
// Datepicker
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
minDate: new Date(2012, 06 - 1, 1),
maxDate:new Date(2012, 09 - 1, 31),
onSelect: function(){
var day1 = ($("#datepicker").datepicker('getDate').getDate()).toString().replace(/(^.$)/,"0$1");
var month1 = ($("#datepicker").datepicker('getDate').getMonth() + 1).toString().replace(/(^.$)/,"0$1");
var year1 = $("#datepicker").datepicker('getDate').getFullYear();
var fullDate = year1 + "/" + month1 + "/" + day1;
var dashDate = year1 + "-" + month1 + "-" + day1;
var str_output = "<a id=\"single_image\" href=\"http://www.lasalle.edu/150/dayinhistory/" + fullDate + ".jpg\" title=\"\"><img src=\"http://www.lasalle.edu/scripts/timthumb/timthumb.php?src=http://www.lasalle.edu/150/dayinhistory/" + fullDate + ".jpg&w=560&h=350&zc=1&a=t\">";
$('#this-day-photo-archive').html(str_output);
var data = 'day=' + dashDate;
$.ajax({
url: 'http://www.lasalle.edu/150/content/day_grab.php',
type: "GET",
data: data,
cache: false,
success: function(html) {
$('#this-day-info').html(html);
console.log (html);
$(".left").click(function() {
$('#datepicker').datepicker( "setDate" , -1d );
});
$(".right").click(function() {
$('#datepicker').datepicker( "setDate" , +1d );
});
}
});
}
});
});
You should replace
$('#datepicker').datepicker( "setDate" , -1d );
with
$('#datepicker').datepicker( "setDate" , "-1d" );
(and the same for +1d)
A link to some examples for confirmation

Categories