Values won't change when I select on dropdown? - javascript

I have a function which creates values for time as I am trying to calculate them, however when I try and change a drop down times I the values don't change as they just stay at 7. The function only loads the default values (time) which is 7 as it is 7 am.
As you can see from the screenshot when the form is loaded it has a time of 7am with the value of 7, but when I change the time to 8:00 it does not show the proper value of 8 and stays at a value of 7
Here is my code:
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
var timeStringToValue = function timeStringToValue(timeStr) {
var _timeStr$match = timeStr.match(/(\d+):(\d+) ([ap]m)/),
_timeStr$match2 = _slicedToArray(_timeStr$match, 4),
hours = _timeStr$match2[1],
minutes = _timeStr$match2[2],
ampm = _timeStr$match2[3];
var ampmHourModifier = ampm === 'pm' ? 12 : 0;
return Number(hours) + ampmHourModifier + minutes / 60;
};
var startMonTimeStr = $('.start-time-monday option:selected').text();
var FinishtMonTimeStr = $('.finish-time-monday option:selected').text();
var startMonValue = timeStringToValue(startMonTimeStr);
console.log(timeStringToValue(startMonTimeStr));
console.log(timeStringToValue(FinishtMonTimeStr));

Related

How to modify code so it doesn't run on reload?

This code,
function dec2hex(dec) {
return dec < 10 ? "0" + String(dec) : dec.toString(16);
}
function generateId(len) {
var arr = new Uint8Array((len || 40) / 2);
window.crypto.getRandomValues(arr);
return Array.from(arr, dec2hex).join("");
}
var random = generateId(64);
document.getElementById("password").innerHTML = random;
setInterval(function() {
function dec2hex(dec) {
return dec < 10 ? "0" + String(dec) : dec.toString(16);
}
function generateId(len) {
var arr = new Uint8Array((len || 40) / 2);
window.crypto.getRandomValues(arr);
return Array.from(arr, dec2hex).join("");
}
var random = generateId(64);
document.getElementById("password").innerHTML = random;
}, 5000);
<div id="password"></div>
will generate a random string every 5 seconds. However, it generate a new string when the page is reloaded. How can I make it NOT generate a random sting on a reload? I have not gotten anything with searches due to the limited queries.
You may use LocalStorage.
The code may look like :
var lastTimeGenerated = window.localStorage.getItem('lastTimeGenerated') === null
? false
: parseInt(window.localStorage.getItem('lastTimeGenerated'));
var generateInterval = 5000;
function dec2hex(dec) {
return dec < 10 ? "0" + String(dec) : dec.toString(16);
}
function generateId(len) {
var arr = new Uint8Array((len || 40) / 2);
window.crypto.getRandomValues(arr);
return Array.from(arr, dec2hex).join("");
}
function launchIntervalFnc() {
intervalFnc();
setInterval(intervalFnc, generateInterval);
}
function intervalFnc() {
var random = generateId(64);
document.getElementById("password").innerHTML = random;
window.localStorage.setItem('lastTimePassword', random);
window.localStorage.setItem('lastTimeGenerated', new Date().getTime());
}
if (lastTimeGenerated !== false && lastTimeGenerated + generateInterval > new Date().getTime()) {
document.getElementById("password").innerHTML = window.localStorage.getItem('lastTimePassword');
setTimeout(launchIntervalFnc, generateInterval - (new Date().getTime() - lastTimeGenerated));
} else {
launchIntervalFnc();
}
<div id="password"></div>

Google calendar sync script

Using a script to sync google sheets with google calendar. It was originally posted on GitHub by DavePar - the original can be seen here - GitHub project
Changed a couple of titles and it works fine.
However, added a column title Stand and getting the following error message. When tried to run the script now
TypeError: Cannot find function getStand in object CalendarEvent.
Have looked through several times and can't see where the problem lies. Can anyone have a look though and point me in the right direction, please?
Here is the slightly modified version:
// Script to synchronize a calendar to a spreadsheet and vice versa.
//
// See https://github.com/Davepar/gcalendarsync for instructions on setting this up.
//
// Set this value to match your calendar!!!
// Calendar ID can be found in the "Calendar Address" section of the Calendar Settings.
var calendarId = 'dtsmike#googlemail.com';
// Set the beginning and end dates that should be synced. beginDate can be set to Date() to use
// today. The numbers are year, month, date, where month is 0 for Jan through 11 for Dec.
var beginDate = new Date(1970, 0, 1); // Default to Jan 1, 1970
var endDate = new Date(2500, 0, 1); // Default to Jan 1, 2500
// Date format to use in the spreadsheet.
var dateFormat = 'd/m/yyyy H:mm';
var titleRowMap = {
'title': 'Title',
'stand': 'Stand',
'description': 'Kit Prep',
'location': 'Location',
'starttime': 'Install',
'endtime': 'Show Finish',
'guests': 'Guests',
'color': 'Color',
'id': 'Id'
};
var titleRowKeys = ['title', 'stand', 'description', 'location', 'starttime', 'endtime', 'guests', 'color', 'id'];
var requiredFields = ['id', 'title', 'starttime', 'endtime'];
// This controls whether email invites are sent to guests when the event is created in the
// calendar. Note that any changes to the event will cause email invites to be resent.
var SEND_EMAIL_INVITES = false;
// Setting this to true will silently skip rows that have a blank start and end time
// instead of popping up an error dialog.
var SKIP_BLANK_ROWS = true;
// Updating too many events in a short time period triggers an error. These values
// were tested for updating 40 events. Modify these values if you're still seeing errors.
var THROTTLE_THRESHOLD = 10;
var THROTTLE_SLEEP_TIME = 75;
// Adds the custom menu to the active spreadsheet.
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [
{
name: "Update from Calendar",
functionName: "syncFromCalendar"
}, {
name: "Update to Calendar",
functionName: "syncToCalendar"
}
];
spreadsheet.addMenu('Calendar Sync', menuEntries);
}
// Creates a mapping array between spreadsheet column and event field name
function createIdxMap(row) {
var idxMap = [];
for (var idx = 0; idx < row.length; idx++) {
var fieldFromHdr = row[idx];
for (var titleKey in titleRowMap) {
if (titleRowMap[titleKey] == fieldFromHdr) {
idxMap.push(titleKey);
break;
}
}
if (idxMap.length <= idx) {
// Header field not in map, so add null
idxMap.push(null);
}
}
return idxMap;
}
// Converts a spreadsheet row into an object containing event-related fields
function reformatEvent(row, idxMap, keysToAdd) {
var reformatted = row.reduce(function(event, value, idx) {
if (idxMap[idx] != null) {
event[idxMap[idx]] = value;
}
return event;
}, {});
for (var k in keysToAdd) {
reformatted[keysToAdd[k]] = '';
}
return reformatted;
}
// Converts a calendar event to a psuedo-sheet event.
function convertCalEvent(calEvent) {
convertedEvent = {
'id': calEvent.getId(),
'title': calEvent.getTitle(),
'stand': calEvent.getStand(),
'description': calEvent.getDescription(),
'location': calEvent.getLocation(),
'guests': calEvent.getGuestList().map(function(x) {return x.getEmail();}).join(','),
'color': calEvent.getColor()
};
if (calEvent.isAllDayEvent()) {
convertedEvent.starttime = calEvent.getAllDayStartDate();
var endtime = calEvent.getAllDayEndDate();
if (endtime - convertedEvent.starttime === 24 * 3600 * 1000) {
convertedEvent.endtime = '';
} else {
convertedEvent.endtime = endtime;
if (endtime.getHours() === 0 && endtime.getMinutes() == 0) {
convertedEvent.endtime.setSeconds(endtime.getSeconds() - 1);
}
}
} else {
convertedEvent.starttime = calEvent.getStartTime();
convertedEvent.endtime = calEvent.getEndTime();
}
return convertedEvent;
}
// Converts calendar event into spreadsheet data row
function calEventToSheet(calEvent, idxMap, dataRow) {
convertedEvent = convertCalEvent(calEvent);
for (var idx = 0; idx < idxMap.length; idx++) {
if (idxMap[idx] !== null) {
dataRow[idx] = convertedEvent[idxMap[idx]];
}
}
}
// Returns empty string or time in milliseconds for Date object
function getEndTime(ev) {
return ev.endtime === '' ? '' : ev.endtime.getTime();
}
// Tests whether calendar event matches spreadsheet event
function eventMatches(cev, sev) {
var convertedCalEvent = convertCalEvent(cev);
return convertedCalEvent.title == sev.title &&
convertedCalEvent.description == sev.description &&
convertedCalEvent.stand == sev.stand &&
convertedCalEvent.location == sev.location &&
convertedCalEvent.starttime.toString() == sev.starttime.toString() &&
getEndTime(convertedCalEvent) === getEndTime(sev) &&
convertedCalEvent.guests == sev.guests &&
convertedCalEvent.color == ('' + sev.color);
}
// Determine whether required fields are missing
function areRequiredFieldsMissing(idxMap) {
return requiredFields.some(function(val) {
return idxMap.indexOf(val) < 0;
});
}
// Returns list of fields that aren't in spreadsheet
function missingFields(idxMap) {
return titleRowKeys.filter(function(val) {
return idxMap.indexOf(val) < 0;
});
}
// Set up formats and hide ID column for empty spreadsheet
function setUpSheet(sheet, fieldKeys) {
sheet.getRange(1, fieldKeys.indexOf('starttime') + 1, 999).setNumberFormat(dateFormat);
sheet.getRange(1, fieldKeys.indexOf('endtime') + 1, 999).setNumberFormat(dateFormat);
sheet.hideColumns(fieldKeys.indexOf('id') + 1);
}
// Display error alert
function errorAlert(msg, evt, ridx) {
var ui = SpreadsheetApp.getUi();
if (evt) {
ui.alert('Skipping row: ' + msg + ' in event "' + evt.title + '", row ' + (ridx + 1));
} else {
ui.alert(msg);
}
}
// Updates a calendar event from a sheet event.
function updateEvent(calEvent, sheetEvent){
sheetEvent.sendInvites = SEND_EMAIL_INVITES;
if (sheetEvent.endtime === '') {
calEvent.setAllDayDate(sheetEvent.starttime);
} else {
calEvent.setTime(sheetEvent.starttime, sheetEvent.endtime);
}
calEvent.setTitle(sheetEvent.title);
calEvent.setDescription(sheetEvent.description);
calEvent.setStand(sheetEvent.stand);
calEvent.setLocation(sheetEvent.location);
// Set event color
if (sheetEvent.color > 0 && sheetEvent.color < 12) {
calEvent.setColor('' + sheetEvent.color);
}
var guestCal = calEvent.getGuestList().map(function (x) {
return {
email: x.getEmail(),
added: false
};
});
var sheetGuests = sheetEvent.guests || '';
var guests = sheetGuests.split(',').map(function (x) {
return x ? x.trim() : '';
});
// Check guests that are already invited.
for (var gIx = 0; gIx < guestCal.length; gIx++) {
var index = guests.indexOf(guestCal[gIx].email);
if (index >= 0) {
guestCal[gIx].added = true;
guests.splice(index, 1);
}
}
guests.forEach(function (x) {
if (x) calEvent.addGuest(x);
});
guestCal.forEach(function (x) {
if (!x.added) {
calEvent.removeGuest(x.email);
}
});
}
// Synchronize from calendar to spreadsheet.
function syncFromCalendar() {
// Get calendar and events
var calendar = CalendarApp.getCalendarById(calendarId);
var calEvents = calendar.getEvents(beginDate, endDate);
// Get spreadsheet and data
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var range = sheet.getDataRange();
var data = range.getValues();
var eventFound = new Array(data.length);
// Check if spreadsheet is empty and add a title row
var titleRow = [];
for (var idx = 0; idx < titleRowKeys.length; idx++) {
titleRow.push(titleRowMap[titleRowKeys[idx]]);
}
if (data.length < 1) {
data.push(titleRow);
range = sheet.getRange(1, 1, data.length, data[0].length);
range.setValues(data);
setUpSheet(sheet, titleRowKeys);
}
if (data.length == 1 && data[0].length == 1 && data[0][0] === '') {
data[0] = titleRow;
range = sheet.getRange(1, 1, data.length, data[0].length);
range.setValues(data);
setUpSheet(sheet, titleRowKeys);
}
// Map spreadsheet headers to indices
var idxMap = createIdxMap(data[0]);
var idIdx = idxMap.indexOf('id');
// Verify header has all required fields
if (areRequiredFieldsMissing(idxMap)) {
var reqFieldNames = requiredFields.map(function(x) {return titleRowMap[x];}).join(', ');
errorAlert('Spreadsheet must have ' + reqFieldNames + ' columns');
return;
}
// Array of IDs in the spreadsheet
var sheetEventIds = data.slice(1).map(function(row) {return row[idIdx];});
// Loop through calendar events
for (var cidx = 0; cidx < calEvents.length; cidx++) {
var calEvent = calEvents[cidx];
var calEventId = calEvent.getId();
var ridx = sheetEventIds.indexOf(calEventId) + 1;
if (ridx < 1) {
// Event not found, create it
ridx = data.length;
var newRow = [];
var rowSize = idxMap.length;
while (rowSize--) newRow.push('');
data.push(newRow);
} else {
eventFound[ridx] = true;
}
// Update event in spreadsheet data
calEventToSheet(calEvent, idxMap, data[ridx]);
}
// Remove any data rows not found in the calendar
var rowsDeleted = 0;
for (var idx = eventFound.length - 1; idx > 0; idx--) {
//event doesn't exists and has an event id
if (!eventFound[idx] && sheetEventIds[idx - 1]) {
data.splice(idx, 1);
rowsDeleted++;
}
}
// Save spreadsheet changes
range = sheet.getRange(1, 1, data.length, data[0].length);
range.setValues(data);
if (rowsDeleted > 0) {
sheet.deleteRows(data.length + 1, rowsDeleted);
}
}
// Synchronize from spreadsheet to calendar.
function syncToCalendar() {
// Get calendar and events
var calendar = CalendarApp.getCalendarById(calendarId);
if (!calendar) {
errorAlert('Cannot find calendar. Check instructions for set up.');
}
var calEvents = calendar.getEvents(beginDate, endDate);
var calEventIds = calEvents.map(function(val) {return val.getId();});
// Get spreadsheet and data
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var range = sheet.getDataRange();
var data = range.getValues();
if (data.length < 2) {
errorAlert('Spreadsheet must have a title row and at least one data row');
return;
}
// Map headers to indices
var idxMap = createIdxMap(data[0]);
var idIdx = idxMap.indexOf('id');
var idRange = range.offset(0, idIdx, data.length, 1);
var idData = idRange.getValues()
// Verify header has all required fields
if (areRequiredFieldsMissing(idxMap)) {
var reqFieldNames = requiredFields.map(function(x) {return titleRowMap[x];}).join(', ');
errorAlert('Spreadsheet must have ' + reqFieldNames + ' columns');
return;
}
var keysToAdd = missingFields(idxMap);
// Loop through spreadsheet rows
var numChanges = 0;
var numUpdated = 0;
var changesMade = false;
for (var ridx = 1; ridx < data.length; ridx++) {
var sheetEvent = reformatEvent(data[ridx], idxMap, keysToAdd);
// If enabled, skip rows with blank/invalid start and end times
if (SKIP_BLANK_ROWS && !(sheetEvent.starttime instanceof Date) &&
!(sheetEvent.endtime instanceof Date)) {
continue;
}
// Do some error checking first
if (!sheetEvent.title) {
errorAlert('must have title', sheetEvent, ridx);
continue;
}
if (!(sheetEvent.starttime instanceof Date)) {
errorAlert('start time must be a date/time', sheetEvent, ridx);
continue;
}
if (sheetEvent.endtime !== '') {
if (!(sheetEvent.endtime instanceof Date)) {
errorAlert('end time must be empty or a date/time', sheetEvent, ridx);
continue;
}
if (sheetEvent.endtime < sheetEvent.starttime) {
errorAlert('end time must be after start time for event', sheetEvent, ridx);
continue;
}
}
// Ignore events outside of the begin/end range desired.
if (sheetEvent.starttime > endDate) {
continue;
}
if (sheetEvent.endtime === '') {
if (sheetEvent.starttime < beginDate) {
continue;
}
} else {
if (sheetEvent.endtime < beginDate) {
continue;
}
}
// Determine if spreadsheet event is already in calendar and matches
var addEvent = true;
if (sheetEvent.id) {
var eventIdx = calEventIds.indexOf(sheetEvent.id);
if (eventIdx >= 0) {
calEventIds[eventIdx] = null; // Prevents removing event below
addEvent = false;
var calEvent = calEvents[eventIdx];
if (!eventMatches(calEvent, sheetEvent)) {
// Update the event
updateEvent(calEvent, sheetEvent);
// Maybe throttle updates.
numChanges++;
if (numChanges > THROTTLE_THRESHOLD) {
Utilities.sleep(THROTTLE_SLEEP_TIME);
}
}
}
}
if (addEvent) {
var newEvent;
sheetEvent.sendInvites = SEND_EMAIL_INVITES;
if (sheetEvent.endtime === '') {
newEvent = calendar.createAllDayEvent(sheetEvent.title, sheetEvent.starttime, sheetEvent);
} else {
newEvent = calendar.createEvent(sheetEvent.title, sheetEvent.starttime, sheetEvent.endtime, sheetEvent);
}
// Put event ID back into spreadsheet
idData[ridx][0] = newEvent.getId();
changesMade = true;
// Set event color
if (sheetEvent.color > 0 && sheetEvent.color < 12) {
newEvent.setColor('' + sheetEvent.color);
}
// Maybe throttle updates.
numChanges++;
if (numChanges > THROTTLE_THRESHOLD) {
Utilities.sleep(THROTTLE_SLEEP_TIME);
}
}
}
// Save spreadsheet changes
if (changesMade) {
idRange.setValues(idData);
}
// Remove any calendar events not found in the spreadsheet
var numToRemove = calEventIds.reduce(function(prevVal, curVal) {
if (curVal !== null) {
prevVal++;
}
return prevVal;
}, 0);
if (numToRemove > 0) {
var ui = SpreadsheetApp.getUi();
var response = ui.Button.YES;
if (numToRemove > numUpdated) {
response = ui.alert('Delete ' + numToRemove + ' calendar event(s) not found in spreadsheet?',
ui.ButtonSet.YES_NO);
}
if (response == ui.Button.YES) {
calEventIds.forEach(function(id, idx) {
if (id != null) {
calEvents[idx].deleteEvent();
Utilities.sleep(20);
}
});
}
}
Logger.log('Updated %s calendar events', numChanges);
}
// Set up a trigger to automatically update the calendar when the spreadsheet is
// modified. See the instructions for how to use this.
function createSpreadsheetEditTrigger() {
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger('syncToCalendar')
.forSpreadsheet(ss)
.onEdit()
.create();
}
// Delete the trigger. Use this to stop automatically updating the calendar.
function deleteTrigger() {
// Loop over all triggers.
var allTriggers = ScriptApp.getProjectTriggers();
for (var idx = 0; idx < allTriggers.length; idx++) {
if (allTriggers[idx].getHandlerFunction() === 'syncToCalendar') {
ScriptApp.deleteTrigger(allTriggers[idx]);
}
}
}

Cross date picker default date issue

hello all i am using the following js code to convert the input type date into three different text boxes for day,month and year.
js
(function () {
var sign = function(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
};
// TODO Calcular año bisiesto
var bisiesto = function(year)
{
return true;
// return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? 1 : 0;
};
$.fn.insertAt = $.fn.insertAt || function(index, $parent) {
return this.each(function() {
if (index === 0) {
$parent.prepend(this);
} else {
$parent.children().eq(index - 1).after(this);
}
});
};
var Crossdp = function(e, o) {
if (e.data("cross-datepicker")) {
return this;
}
e.attr("type", "text");
o = $.extend({}, $.fn.cdp.defaults, o);
if(o.hideInput)
e.hide();
var cnt = $("<div>").addClass(o.classes.container || "").data("input", e).insertBefore(e);
// Data
var days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Read format
var d = $("<select>").addClass(o.classes.controls || "").addClass(o.classes.days || ""),
m = $("<select>").addClass(o.classes.controls || "").addClass(o.classes.months || ""),
y = $("<select>").addClass(o.classes.controls || "").addClass(o.classes.year || "");
/**
* Gets the format metadata.
*/
var getFormat = function(format) {
var f = {},
last = "",
order = 0,
elements = {
"d": d,
"m": m,
"y": y
};
for(var i = 0, of=format; i < of.length; i++) {
var c = of[i];
if(last == c) {
f[c].count ++;
}
else if(c == "d" || c == "y" || c == "m") {
f[c] = {
"count": 1,
"order": order++,
"e": elements[c]
};
elements[c].data("order", f[c].order);
last = c;
}
if(order > 3) {
throw "Invalid date format";
}
}
return f;
};
var iF = getFormat(o.inputFormat),
f = getFormat(o.format);
for(var i in f) {
f[i].e.appendTo(cnt);
}
cnt.sort(function(a, b) {
if(a.data("order") > b.data("order")) {
return 1;
}
else if(a.data("order") < b.data("order")) {
return -1;
}
else {
return 0;
}
});
// Helpers
/**
* Format a numeric day to string.
*/
var formatDay = function(day, format) {
var text = String(day),
c = format || f.d.count;
while(c > text.length) {
text = "0" + text;
}
return text;
};
/**
* Format a numeric month to string.
*/
var formatMonth = function(month, format) {
if(month > 12) {
throw "Invalid month: "+month;
}
var c = format || f.m.count,
text = String(month);
if(c == 2) {
if(text.length == 1) {
text = "0" + text;
}
}
else if(c == 3) {
text = o.months[i-1].substr(0, 3);
}
else if(c == 4) {
text = o.months[i-1];
}
else {
throw "Invalid month format";
}
return text;
};
/**
* Format a numeric month to string.
*/
var formatYear = function(year, format) {
var text = String(year),
c = format || f.y.count;
if(c == 2) {
text = text.substr(text.length-2, 2);
}
else if(c != 4) {
throw "Invalid year format";
}
return text;
};
var parseYear = function(date, format) {
// TODO
};
// Update input function
var formatDate = function(resultFormat, readFormat, years, months, days) {
var a = ["d", "m", "y"],
result = resultFormat;
if(typeof days === 'string')
days = parseInt(days);
if(typeof months === 'string')
months = parseInt(months);
if(typeof years === 'string')
years = parseInt(years);
for(var i = 0; i < a.length; i++) {
var ch = a[i], /* Example: a[0]='d' */
format = readFormat[ch], /* Example: uF['d']='dd' */
word = "",
formatted = "";
for(var j = 0; j < format.count; j++) {
word += ch;
}
if(ch == "d") {
formatted = formatDay(days, format.count);
}
else if(ch == "m") {
formatted = formatMonth(months, format.count);
}
else {
formatted = formatYear(years, format.count);
}
result = result.replace(word, formatted);
}
return result;
};
var updateInput = function() {
e.val(formatDate(o.inputFormat, iF, y.val(), m.val(), d.val()));
};
this.updateInput = function() {
updateInput();
};
var updateFromInput = function() {
// TODO
};
// Generate 3 selects
/* Days */
d.data("days", 0);
/**
* Days of determinated month.
*/
var generateDays = function(month) {
if(d.data("days") == days[month-1]) {
return;
}
var selected = parseInt(d.val() || "1");
d.html("");
if(month == 0) {
return;
}
if(o.addNullOption) {
d.append("<option value=''>"+o.nullOptionText+"</option>");
}
for(var i = 1; i <= days[month-1]; i++) {
$("<option>").attr("value", i).text(formatDay(i)).appendTo(d);
}
d.val(selected);
};
d.change(function() {
updateInput();
});
generateDays(1);
/* Months */
m.change(function() {
// Regenerate days
generateDays(parseInt($(this).val()));
updateInput();
});
if(o.addNullOption) {
m.append("<option value='0'>"+o.nullOptionText+"</option>");
}
for(var i = 1; i <= 12; i++) {
m.append("<option value='"+i+"'>"+formatMonth(i)+"</option>");
}
/* Years */
var from,
to;
if(typeof o.years[0] == 'string') {
var current = new Date().getFullYear(),
count;
if(o.years.length == 3) {
current += o.years[1];
count = o.years[2];
}
else {
count = o.years[1];
}
for(var i = current; i != current + count; i += sign(count)) {
y.append("<option value='"+i+"'>"+formatYear(i)+"</option>");
}
}
else {
for(var i = o.years[0]; i != o.years[1]; i += sign(o.years[1]-o.years[0])) {
y.append("<option value='"+i+"'>"+formatYear(i)+"</option>");
}
}
y.change(function() {
updateInput();
});
// Save
this.inputs = {
d: d,
y: y,
m: m
};
// Finish
if(e.data("initial-day")) {
$(function() {
$.fn.cdp.statics.fns.set(e, [
e.data("initial-year"),
e.data("initial-month"),
e.data("initial-day")]);
});
}
updateInput();
e.data("cross-datepicker", this);
};
$.fn.cdp = function (o, arg) {
var e = $(this);
if (e.length == 0) {
return this;
}
else if (e.length > 1) {
e.each(function () {
$(this).cdp(o);
});
return this;
}
if(!e.is("input")) {
throw "You can apply Cross-DatePicker only on an 'input' element";
}
if(typeof o === 'string') {
var st = $.fn.cdp.statics;
if(!st.fns[o]) {
console.error("Unknown function "+o);
}
st.fns[o](e, arg);
return this;
}
var cdp = new Crossdp(e, o);
return this;
}
$.fn.cdp.defaults = {
hideInput: true,
format: "d/mmm/yyyy",
inputFormat: "yyyy-mm-dd",
years: ["now", -100], // [initial year, final year] or ["now", relative years count] or ["now", relative years from, relative years count]
months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"],
addNullOption: false,
nullOptionText: "Select",
classes: {
container: "cdp-container",
controls: "cdp-select",
days: "cdp-d",
months: "cdp-m",
years: "cdp-y"
}
};
$.fn.cdp.statics = {
fns: {
set: function(e, arg) {
var st = $.fn.cdp.statics,
obj = e.data("cross-datepicker"),
y,m,d;
if($.isArray(arg)) {
y = arg[0];
m = arg[1];
d = arg[2];
}
else if(typeof arg === 'string') {
var array = arg.split("-");
y = parseInt(array[0]);
m = parseInt(array[1]);
d = parseInt(array[2]);
}
else {
y = arg.year || arg.y;
m = arg.month || arg.m;
d = arg.day || arg.d;
}
obj.inputs.y.val(String(y));
obj.inputs.m.val(String(m));
obj.inputs.d.val(String(d));
obj.updateInput();
}
}
};
})();
how to implement
html
<input type="date" data-initial-day="20" data-initial-year="2010" data-initial-month="64" />
<!-- Required scripts -->
<script src='https://code.jquery.com/jquery-2.1.0.min.js'></script>
<script src='../src/cross-datepicker.js'></script>
<script>
$(function() {
$("input[type='date']").cdp();
});
</script>
the problem is that the code works great when defined data-initial-year for month and day also but when i want to show the default none selected date like select day select month and select year it shows blank or 0 .
i dont know how to solve this i have tried to solve the problem by adding some text into the js file but no help .
if you can suggest me something it would be great.
The plugin code needs to check if an entry is valid before setting it.
First off, set the addNullOption to true so that a "Select" text is visible.
$(function() {
$("input[type='date']").cdp({
addNullOption : true,
nullOptionText: "Select"
});
});
Then modify the last function $.fn.cdp.statics with the "check valid" code included below (demo):
$.fn.cdp.statics = {
fns: {
set: function(e, arg) {
var st = $.fn.cdp.statics,
obj = e.data("cross-datepicker"),
y,m,d;
if($.isArray(arg)) {
y = arg[0];
m = arg[1];
d = arg[2];
}
else if(typeof arg === 'string') {
var array = arg.split("-");
y = parseInt(array[0]);
m = parseInt(array[1]);
d = parseInt(array[2]);
}
else {
y = arg.year || arg.y;
m = arg.month || arg.m;
d = arg.day || arg.d;
}
// check valid
if ( obj.inputs.y.find('option[value="' + y + '"]').length ) {
obj.inputs.y.val(String(y));
}
if ( obj.inputs.m.find('option[value="' + m + '"]').length ) {
obj.inputs.m.val(String(m));
}
if ( obj.inputs.d.find('option[value="' + d + '"]').length ) {
obj.inputs.d.val(String(d));
}
obj.updateInput();
}
}
};
To show "Select" in the other selects, I ended up adding the following code because the year select didn't have a null option:
if (o.addNullOption) {
y.append("<option value='0'>"+o.nullOptionText+"</option>");
}
and changing the "check valid" code to:
// check valid
y = obj.inputs.y.find('option[value="' + y + '"]').length ? y : 0;
obj.inputs.y.val(String(y));
m = obj.inputs.m.find('option[value="' + m + '"]').length ? m : 0;
obj.inputs.m.val(String(m));
d = obj.inputs.d.find('option[value="' + d + '"]').length ? d : 0;
obj.inputs.d.val(String(d));
Get the full code from this updated demo.

getting html input value inside javascript class

i am new to javascript and im making a BMI calculator. im making a class in javascript to produce the calculations. currently users could input their height (in feet and inches) and weight. when i run a method within my class. it keeps saying this.feet = null instead of grabbing the value from the input. my javascript code is below. result() is in my html for the submit button.
function calculator(feet,inches,weight) {
this.feet = feet.value;
this.inches = inches.value;
this.weight = weight.value;
this.validateInput = function() {
var errors = [];
if(isNaN(this.feet) || this.feet < 0) {
errors.push("Feet");
}
else {
return this.feet
};
if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) {
errors.push("Inches")
}
else {
return this.inches;
};
if(isNaN(this.weight) || this.weight < 0) {
errors.push("Weight");
}
else {
return this.weight
}
};
this.inchesConverter = function() {
this.feet = parseFloat(feet);
this.inches = parseFloat(inches);
return parseInt(this.feet*12+this.inches);
};
this.bmi = function() {
var height = this.inchesConverter();
var validater = this.validateInput();
for(r = 0; r < errors.length; r++){
if(errors.length > 0) {
return errors[r] + " must be a valid positive number.";
}
else {
parseFloat((validateWeight * 703) / (Math.pow(height, 2))).toFixed(1);
}
}
};
};
var getWeight = document.getElementById('txtWeight');
var getFeet = document.getElementById('txtHeightFeet');
var getInches = document.getElementById('txtHeightInches');
var test = new calculator(getFeet, getInches, getWeight);
function result() {
document.getElementById("lblBMI").innerHTML(test.bmi());
}
Instead of assigning feet.value to this.feet try assigning feet.getAttribute('value')
If you console.log(feet) does it show the proper DOM element?
There is no need to declare the variables with "this."
function calculator(paraFeet,paraInches,paraWeight) {
var feet = paraFeet.value;
var inches = paraInches.value;
var weight = paraWeight.value;
...
you can now remove "this." from every of these variables inside your function
Every browser has JavaScript console on which you can debug your code.
I have some fun to fix it here or there but also you should try it yourself.
Anyway here it is:
function calculator(weight, feet, inches) {
this.weight = weight;
this.feet = feet;
this.inches = inches;
this.validateInput = function() {
var errors = [];
if (!this.validNumber(this.weight, 1000)) {
errors.push("Invalid weight.");
}
if (!this.validNumber(this.feet, 10)) {
errors.push("Invalid hight in feet.");
}
if (!this.validNumber(this.inches, 11)) {
errors.push("Invalid hight in inches.")
}
return errors;
};
this.validNumber = function(num, max) {
if (num.length > 0 && !isNaN(num)) {
var number = parseInt(num);
return number > 0 && number < max + 1;
}
return false;
}
this.displayErrors = function(errors) {
var html = "";
for (error of errors)
html += error + "<br/>";
return html;
};
this.inchesConverter = function() {
var feet = parseInt(this.feet);
var inches = parseInt(this.inches);
return feet * 12 + inches;
};
this.bmi = function() {
var errors = this.validateInput();
if (errors.length > 0) {
return this.displayErrors(errors);
}
var height = this.inchesConverter();
return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1);
};
};
function result() {
var getWeight = document.getElementById('txtWeight').value;
var getFeet = document.getElementById('txtHeightFeet').value;
var getInches = document.getElementById('txtHeightInches').value;
var test = new calculator(getWeight, getFeet, getInches);
document.getElementById("lblBMI").innerHTML = test.bmi();
return false;
}
<span>
<label>Weight</label>
<input id="txtWeight">
</span>
<span>
<label>HeightFeet</label>
<input id="txtHeightFeet">
</span>
<span>
<label>HeightInches</label>
<input id="txtHeightInches">
</span>
<button id='run' onClick="return result();">Calculate</button>
<div id="lblBMI"></div>
Figured out what my issue was. The problem arose from my for loop. Working code is posted below!
function calculator(feet,inches,weight) {
this.feet = feet.value;
this.inches = inches.value;
this.weight = weight.value;
this.validateInput = function() {
var errors = [];
if(isNaN(this.feet) || this.feet < 0 || this.feet == "") {
errors.push("feet");
};
if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) {
errors.push("inches")
};
if(isNaN(this.weight) || this.weight < 0 || this.weight == "") {
errors.push("weight");
};
return errors;
console.log(errors);
};
this.inchesConverter = function() {
var parseFeet = parseFloat(this.feet);
var parseInches = parseFloat(this.inches);
return parseInt(parseFeet*12+parseInches);
};
this.bmi = function() {
var height = this.inchesConverter();
var errors = this.validateInput();
if(errors.length > 0) {
for(r = 0; r < errors.length; r++){
return "Please enter a correct number for " + errors[r];
};
}
else {
return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1);
};
};
};
function result(){
var getWeight = document.getElementById('txtWeight');
var getFeet = document.getElementById('txtHeightFeet');
var getInches = document.getElementById('txtHeightInches');
var test = new calculator(getFeet, getInches, getWeight);
document.getElementById("lblBMI").innerHTML = test.bmi();
};

JavaScript TimeSequence Array approximate access mechanism

I try to implement a TimeSequence Array approximate access mechanism in JavaScript.
My project want to record mutable value with time-stamp on every event in an array, in time sequence manner.
Say, if the event occurs on 2014/10/05 12:59:59 001,
val[20141005125959001] = 4;
on 2014/10/05 13:00:05 234,
val[20141005130005234] = 7;
Then, later,
the code is supposed to to access val approximately with a function, that is,
getVal(20141005125959001) = 4;
getVal(20141005130005234) = 7;
and in addition, when the function access val array with unassigned index such as
val[20141005125959002] or val[201410051300000100], the smart function returns
getVal(20141005125959002) = 4 // since this is prior timing that the value is going to become 7
To implement such a function, I wonder what would be the smartest way.
An obvious simple method is scan incrementally whole array index started from the required index val, and that would work when the event is so frequent (mill second base), however, once the event is infrequent, the mill-second incremental index scan is not effective.
Probably I need to add index of index, but I would like to hear smart opinion.
Any idea? thanks.
PS
I post my own solution
See below
recording logic
var compute = function()
{
var moment = require('moment');
var utc = moment().utc();
var YY = utc.year() - 2000 + '';
var MM = utc.month() + 1 + '';
var DD = utc.date() + '';
var HH = utc.hour() + '';
var mm = utc.minute() + '';
var ss = utc.second() + '';
var msc = utc.millisecond() + '';
log(YY);
log(MM);
log(DD);
log(HH);
log(mm);
log(ss);
log(msc);
var preObj = this;
if (preObj[YY] === undefined)
{
preObj[YY] = {};
}
if (preObj[YY][MM] === undefined)
{
preObj[YY][MM] = {};
}
if (preObj[YY][MM][DD] === undefined)
{
preObj[YY][MM][DD] = {};
}
if (preObj[YY][MM][DD][HH] === undefined)
{
preObj[YY][MM][DD][HH] = {};
}
if (preObj[YY][MM][DD][HH][mm] === undefined)
{
preObj[YY][MM][DD][HH][mm] = {};
}
if (preObj[YY][MM][DD][HH][mm][ss] === undefined)
{
preObj[YY][MM][DD][HH][mm][ss] = {};
}
preObj[YY][MM][DD][HH][mm][ss][msc] = preObj.val;
};
reading logic
var value = function(utc)
{
log('--value--');
var Obj = this;
var YY = utc.year() - 2000;
var MM = utc.month() + 1;
var DD = utc.date();
var HH = utc.hour();
var mm = utc.minute();
var ss = utc.second();
var msc = utc.millisecond();
log(YY);
log(MM);
log(DD);
log(HH);
log(mm);
log(ss);
log(msc);
var iYY = YY;
while (iYY >= 0)
{
if (Obj[iYY] === undefined)
{
log('YY NOT found');
iYY--;
MM = 12;
}
else
{
log('YY found');
var iMM = MM;
while (iMM >= 1)
{
if (Obj[iYY][iMM] === undefined)
{
log('MM NOT found');
iMM--;
DD = 31;
}
else
{
log('MM found');
var iDD = DD;
while (iDD >= 1)
{
if (Obj[iYY][iMM][iDD] === undefined)
{
log('DD NOT found');
iDD--;
HH = 23;
}
else
{
log('DD found');
var iHH = HH;
while (iHH >= 0)
{
if (Obj[iYY][iMM][iDD][iHH] === undefined)
{
log('HH NOT found');
iHH--;
mm = 59;
}
else
{
log('HH found');
var imm = mm;
while (imm >= 0)
{
if (Obj[iYY][iMM][iDD][iHH][imm] === undefined)
{
log('mm NOT found');
imm--;
ss = 59;
}
else
{
log('mm found');
var iss = ss;
while (iss >= 0)
{
if (Obj[iYY][iMM][iDD][iHH][imm][iss] === undefined)
{
log('ss NOT found');
iss--;
msc = 999;
}
else
{
log('ss found');
var imsc = msc;
while (imsc >= 0)
{
log(imsc);
if (Obj[iYY][iMM][iDD][iHH][imm][iss][imsc] === undefined)
{
log('msc NOT found');
imsc--;
}
else
{
log('msc found');
return Obj[iYY][iMM][iDD][iHH][imm][iss][imsc];
}
}
iss--;
msc = 999;
}
}
imm--;
ss = 59;
}
}
iHH--;
mm = 59;
}
}
iDD--;
HH = 23;
}
}
iMM--;
DD = 31;
}
}
iYY--;
MM = 12;
}
}
return null;
};

Categories