Angularjs tiny display bug with ng-if - javascript

I have a small bug with my display logic. User selects job length as step 1 then clicks on a cell to determine availability. Everything works but I need Selected to show up on the other cells. I think some sort of boolean I have to attach i'm not sure. Assume for now jobLength=3 (this comes anyway from the HTML5 custom slider not displayed below but is just above the table as Step 1).How do I get Selected to show up.
Here's the code.
<tbody>
<tr ng-repeat="hour in workhours" ng-init="selectedIndex=$index">
<td>{{hour}}:00 - {{hour+1}}:00</td>
<td class="hidden-xs" ng-class = "{ 'full' : !entry.HoursAvailable.includes(hour),
'selected' : renderGreen(selectedIndex, $index, jobLength)}"
ng-click = "checkSlotAvailability(hour, jobLength, entry, data)"
ng-repeat= "entry in data.calendar">
<!-- /* ============ -->
<!-- Display Logic -->
<!-- =============== -->
<span ng-if="entry.HoursAvailable.includes(hour)
&& !renderGreen(selectedIndex, $index, jobLength)
&& !(selectedIndex == selectedRow
&& $index == selectedColumn)">
Available
</span>
<span ng-if="entry.HoursAvailable.includes(hour)
&& renderGreen(selectedIndex, $index, jobLength)
&& $index == selectedColumn
&& selectedIndex == selectedRow
<!-- I added this check slot f(x) to render table dynamically when user adjusts job length -->
&& checkSlotAvailability(hour, jobLength, entry, data)">
Selected
</span>
<span ng-if="entry.HoursAvailable.includes(hour)
&& !renderGreen(selectedIndex, $index, jobLength)
&& selectedIndex == selectedRow
&& $index == selectedColumn">
Unavailable
</span>
<span ng-if="!entry.HoursAvailable.includes(hour)">
Full
</span>
</td>
</tr>
</tbody>
controller
(function() {
"use strict";
angular
.module("availability")
.controller("availabilityController", function($scope, $http){
$scope.data = {};
$scope.data.response = "Available";
$scope.workhours = Array.from({length:9}).map((_, i)=> i + 9); // creating all possible working hours in a day (9-17)
$http.get('../api/availability.json')
.then( function(response){
$scope.data.calendar = response.data;
});
function setBuffer(date){
var today = formatDateToString(new Date('2016-05-18T11:27:00'));
var bufferTime = 1;
if(date == today){
bufferTime = 2;
}
return bufferTime;
}
function formatDateToString(date){
var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
var yyyy = date.getFullYear();
return (yyyy + "-" + MM + "-" + dd);
}
function getRowAndColumn(row, column){
$scope.selectedRow = row;
$scope.selectedColumn = column;
}
$scope.renderGreen = function(selectedIndex, $index, jobLength){
if( $index == $scope.selectedColumn
&& selectedIndex >= $scope.selectedRow
&& selectedIndex <= ($scope.selectedRow + jobLength - 1) && $scope.data.response == "Available")
return true;
else
return false;
}
/* ===========================
Check Availabiliy function
============================== */
$scope.checkSlotAvailability = function(time, jobLength, date, availability) {
var date = date.Date;
var calendar = availability.calendar;
var response = "";
var buffer = setBuffer(date);
var selectedIndex = time - 9;
if( jobLength < 1 || jobLength > 5 ){
alert("Please enter job length from 1 to 5");
response = "Available";
}else {
for( var i = 0; i < calendar.length; i++ ){
getRowAndColumn(selectedIndex, i);
if( date == calendar[i].Date ){
if( time < 9 || time > 17 ){ // Can't book before 9am or after 5pm. Code should never reach here.
response = "Unavailable";
break;
}else {
for( var j = 0; j < calendar[i].HoursAvailable.length; j++){
if( time == calendar[i].HoursAvailable[j]){
if( ( time == 9 || time == 17 ) && calendar[i].HoursAvailable[j]
|| time - buffer < 9
|| time == calendar[i].HoursAvailable[j]
&& time - buffer == calendar[i].HoursAvailable[j - buffer]
&& time + buffer == calendar[i].HoursAvailable[j + buffer] ){
for( var k = j; k < calendar[i].HoursAvailable.length; k++ ){
if( time >= 13 && time == calendar[i].HoursAvailable[k] && time + jobLength <= 18
&& time - buffer == calendar[i].HoursAvailable[k - buffer] //5pm
|| (time + jobLength + (buffer - 1)) == calendar[i].HoursAvailable[k + jobLength + (buffer - 1)]
&& time - buffer == calendar[i].HoursAvailable[k - buffer]
|| (time + jobLength + (buffer - 1)) == calendar[i].HoursAvailable[k + jobLength + (buffer - 1)] ){ //9am
response = "Available";
break;
}else if( k == calendar[i].HoursAvailable.length - 1 ){
response = "Unavailable";
}
}
break;
}else{
response = "Unavailable";
break;
}
}else if( j == calendar[i].HoursAvailable.length - 1 ){ //no available slot
response = "Full";
}
}
break;
}
}else if( i == calendar.length - 1 ){ //no available date
response = "Full";
break;
}
}
}
$scope.data.response = response;
return response;
};
});
})();

Related

Get array values from column

If my function gets the values of one column, say column I, how can I tell it to instead get the values of the column to the right (J) instead of I:K?
function headerSearch(e, activeCell, activeRow, activeCol, data, mode, secMode, terMode) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var foundValues = [];
var forConR = data.length;
var forConC = data[0].length;
Logger.log("data[0] = " + data[0]);
for (var i = 1; i < forConR; i++) {
for (var j = 0; j < forConC; j++) {
if (activeCell != "" && activeCol == 2 && data[0][j].indexOf(mode) > -1) {
if (activeCell.getValue() == data[0][j]) {
foundValues.push(data[i][j]);
}
} else if (activeCell != "" && activeCol == 3 && data[0][j].indexOf(mode) > -1 && data[i][j] != "") {
foundValues.push(data[i][j]);
Logger.log("foundValues = " + foundValues);
}
}
}
if (foundValues != "") {
var validationRule = SpreadsheetApp.newDataValidation().requireValueInList(foundValues).build();
activeCell.offset(0, 1).setDataValidation(validationRule);
}
}
EDIT:
I tried adding foundValues.push(data[i][j+1]); which gets me out of the first column (I), but then of course adds the NEXT column (L) that I don't want either. I'm just not sure how to isolate the column index. Once I figure that out, I'm sure it's just a matter of adding +1 or something to OFFSET to the column to the right.
You have two for loops - one of them iterating through all rows, the second through all columns of data
What you want instead is to retrieve only ONE column of data rather than iterating through ALL of them
You can do it by simply dropping the second for loop and instead hardcoding the value for j
If you are itnerested in the second column of your range - the column index should be 1 (since array indices start with 0)
Without having a deeper knowledge of the purpose of your if conditions and assuming that you use them only to assess the value in column J, you can modify your code as following:
...
for (var i = 1; i < forConR; i++) {
var j = 1;
if (activeCell != "" && activeCol == 2 && data[0][j].indexOf(mode) > -1) {
if (activeCell.getValue() == data[0][j]) {
foundValues.push(data[i][j]);
}
} else if (activeCell != "" && activeCol == 3 && data[0][j].indexOf(mode) > -1 && data[i][j] != "") {
foundValues.push(data[i][j]);
Logger.log("foundValues = " + foundValues);
}
}
...
I rearranged my if statements and added one to isolate the "mode" column (B) selected. At that point, I could add j + 1 to get the following column values for the next data validation selection.
function headerSearch(e, activeCell, activeRow, activeCol, data, mode, secMode, terMode) {
var foundValues = [];
var forConR = data.length;
var forConC = data[0].length;
if (activeCell != "") {
for (var i = 1; i < forConR; i++) {
for (var j = 0; j < forConC; j++) {
if (data[0][j] == mode && data[i][j] != "") {
var modeCol = j;
}
if (activeCol == 2 && data[i][j] != "") {
if (activeCell.getValue() == data[0][j]) {
foundValues.push(data[i][j]);
}
} else if (activeCol == 3 && data[0][j].indexOf(mode) > -1 && data[i][j] != "" && data[0][modeCol + 1].indexOf(mode) > -1) {
foundValues.push(data[i][modeCol + 1]);
} else if (activeCol == 4 && data[0][j].indexOf(mode) > -1 && data[i][j] != "" && data[0][modeCol + 2].indexOf(mode) > -1) {
foundValues.push(data[i][modeCol + 2]);
}
}
}
}
if (foundValues != "") {
var validationRule = SpreadsheetApp.newDataValidation().requireValueInList(foundValues).build();
activeCell.offset(0, 1).setDataValidation(validationRule);
}
}

Making a date mask react with javascript: If i press simultaneous numbers i lost the mask

I'm trying to make a mask react date dd/mm/yyyy to a custom date input.
If i press the keys slow, the mask is setted correct dd/mm/yyyy, but supposing i press the numbers rapid, my mask is breaking
This is my component:
<DateInput
name="date"
placeholder="Data"
value={this.props.data}
dateFormat="DD/MM/YYYY"
onChange={this.props.changeDataTarefa}
animation="none"
onKeyUp={() => this.props.changeDataTarefaMask(this.fixDatePattern(this.props.data))}/>
this is my functions:
fixDatePattern(currDate) {
var currentDate = currDate;
if (currentDate){
var currentLength = currentDate.length;
var lastNumberEntered = currentDate[currentLength - 1];
}
if (!this.isNumber(lastNumberEntered) && currentDate) {
return currentDate.substring(0, currentLength - 1);
}
if (currentLength > 10) {
return currentDate.substring(0, 10);
}
let dateCountTracker = 0
if (currentLength == 1 && currentDate > 1) {
var transformedDate = "0" + currentDate + '/';
dateCountTracker = 2;
currentLength = transformedDate.length;
return transformedDate;
} else if (currentLength == 4 && currentDate[3] > 3) {
let transformedDate = currentDate.substring(0, 3) + "0" + currentDate[3] + '/';
dateCountTracker = 5;
currentLength = transformedDate.length;
return transformedDate;
} else if (currentLength == 2 && (dateCountTracker != 2 && dateCountTracker != 3)) {
dateCountTracker = currentLength;
return currentDate + '/';
} else if (currentLength == 5 && (dateCountTracker != 5 && dateCountTracker != 6)) {
dateCountTracker = currentLength;
return currentDate + '/';
}
dateCountTracker = currentLength;
return currentDate;
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Instead of using keyup, use keypress event on input. And you could also use react input mask plugin for same.
You can use below code for key press event and please check working stackblitz demo.
render() {
return (
<div>
<span>Date : </span>
<input type="text" maxLength="10" placeHolder="dd/mm/yyyy" onKeyPress={this.onKeyPress}/>
</div>
)
}
onKeyPress(e){
let input = e.target;
if(e.charCode < 47 || e.charCode > 57) {
e.preventDefault();
}
var len = input.value.length;
if(len !== 1 || len !== 3) {
if(e.charCode == 47) {
e.preventDefault();
}
}
if(len === 2) {
input.value += '/';
}
if(len === 5) {
input.value += '/';
}
}
You could use below react input mask plugins to achieve requirement.
imaskjs and react-input-mask

input 0 is not defined stack:reference error

I am using scw date picker library. Javascript code that I used for a long time doesn't work now. onclick function of input works on the first row but doesn't work on second and other rows.
I created the inputs dynamically with javascript codes.
JavaScript Codes
function AddRow(tbody_id, satir_id)
{
var tbody = document.getElementById(tbody_id);
var row = document.createElement("tr");
row.id = "s" + satir_id;
var input0 = document.createElement("input");
input0.id = row.id + "_i0";
input0.name = "satir[" + satir_id+ "][0]";
input0.className = "text";
input0.size = "11";
input0.onclick = function onclick()
{
scwNextAction = tmp.runAfterSCW(this);
scwShow(this, event);
}
}
At this input0.onclick method work on first row. But it doesn't work on second and another rows.
Error is like below:
input0 is not defined
stack:"ReferenceError: input0 is not defined↵ at eval (eval at positiontip (http://portaltest.gural.tr/phpgroupware/kys/siparis/ortak/kutuphane/form.js?v2.0.1035:1:1), :1:1)↵ at HTMLDocument.positiontip (http://portaltest.gural.tr/phpgroupware/kys/siparis/ortak/kutuphane/form.js?v2.0.1035:334:21)"
The same code works at internet explorer but doesn't work at google crome. There is reference error at both of them(internet explorer,google chrome).
Do you think how can I fix this situation?
Can you try to addEventListener instead of using onclick property
function AddRow(tbody_id, satir_id)
{
var tbody = document.getElementById(tbody_id);
var row = document.createElement("tr");
row.id = "s" + satir_id;
var input0 = document.createElement("input");
input0.id = row.id + "_i0";
input0.name = "satir[" + satir_id+ "][0]";
input0.className = "text";
input0.size = "11";
input0.addEventlistener("click", function(evt) {
scwNextAction = tmp.runAfterSCW(this);
scwShow(this, evt);
})
}
Else, do you have reference to input0 in tmp.runAfterSCW() or scwShow() ?
I have scw.js for scw date picker library.
for runsAfterSCW function:
Function.prototype.runsAfterSCW =
function() {var func = this,
args = new Array(arguments.length);
for (var i=0;i<args.length;++i) {args[i] = arguments[i];}
return function()
{// concat/join the two argument arrays
for (var i=0;i<arguments.length;++i) {args[args.length] = arguments[i];}
return (args.shift()==scwTriggerEle)?func.apply(this, args):null;
};
};
For scwShow function:
function scwShow(scwEle,scwSource)
{if (!scwSource) {scwSource = window.event;}
if (scwSource.tagName) // Second parameter isn't an event it's an element
{var scwSourceEle = scwSource;
if (scwID('scwIE')) {window.event.cancelBubble = true;}
else {scwSourceEle.parentNode.addEventListener('click',scwStopPropagation,false);}
}
else // Second parameter is an event
{var scwSourceEle = (scwSource.target)
?scwSource.target
:scwSource.srcElement;
// Stop the click event that opens the calendar from bubbling up to
// the document-level event handler that hides it!
if (scwSource.stopPropagation) {scwSource.stopPropagation();}
else {scwSource.cancelBubble = true;}
}
scwTriggerEle = scwSourceEle;
// Take any parameters that there might be from the third onwards as
// day numbers to be disabled 0 = Sunday through to 6 = Saturday.
scwParmActiveToday = true;
for (var i=0;i<7;i++)
{scwPassEnabledDay[(i+7-scwWeekStart)%7] = true;
for (var j=2;j<arguments.length;j++)
{if (arguments[j]==i)
{scwPassEnabledDay[(i+7-scwWeekStart)%7] = false;
if (scwDateNow.getDay()==i) {scwParmActiveToday = false;}
}
}
}
// If no value is preset then the seed date is
// Today (when today is in range) OR
// The middle of the date range.
scwSeedDate = scwDateNow;
// Find the date and Strip space characters from start and
// end of date input.
var scwDateValue = '';
if (scwEle.value) {scwDateValue = scwEle.value.replace(/^\s+/,'').replace(/\s+$/,'');}
else {if (typeof scwEle.value == 'undefined')
{var scwChildNodes = scwEle.childNodes;
for (var i=0;i<scwChildNodes.length;i++)
{if (scwChildNodes[i].nodeType == 3)
{scwDateValue = scwChildNodes[i].nodeValue.replace(/^\s+/,'').replace(/\s+$/,'');
if (scwDateValue.length > 0)
{scwTriggerEle.scwTextNode = scwChildNodes[i];
scwTriggerEle.scwLength = scwChildNodes[i].nodeValue.length;
break;
}
}
}
}
}
// Set the language-dependent elements
scwSetDefaultLanguage();
scwID('scwDragText').innerHTML = scwDrag;
scwID('scwMonths').options.length = 0;
for (var i=0;i<scwArrMonthNames.length;i++)
{scwID('scwMonths').options[i] = new Option(scwArrMonthNames[i],scwArrMonthNames[i]);}
scwID('scwYears').options.length = 0;
for (var i=0;i<scwDropDownYears;i++)
{scwID('scwYears').options[i] = new Option((scwBaseYear+i),(scwBaseYear+i));}
for (var i=0;i<scwArrWeekInits.length;i++)
{scwID('scwWeekInit' + i).innerHTML = scwArrWeekInits[(i+scwWeekStart)%scwArrWeekInits.length];}
if (((new Date(scwBaseYear + scwDropDownYears, 0, 0)) > scwDateNow &&
(new Date(scwBaseYear, 0, 0)) < scwDateNow) ||
(scwClearButton && (scwEle.readOnly || scwEle.disabled))
) {scwID('scwFoot').style.display = '';
scwID('scwNow').innerHTML = scwToday + ' ' + scwDateNow.scwFormat(scwDateDisplayFormat);
scwID('scwClearButton').value = scwClear;
if ((new Date(scwBaseYear + scwDropDownYears, 0, 0)) > scwDateNow &&
(new Date(scwBaseYear, 0, 0)) < scwDateNow
) {scwID('scwNow').style.display = '';
if (scwClearButton && (scwEle.readOnly || scwEle.disabled))
{scwID('scwClear').style.display = '';
scwID('scwClear').style.textAlign = 'left';
scwID('scwNow').style.textAlign = 'right';
}
else {scwID('scwClear').style.display = 'none';
scwID('scwNow').style.textAlign = 'center';
}
}
else {scwID('scwClear').style.textAlign = 'center';
scwID('scwClear').style.display = '';
scwID('scwNow').style.display = 'none';
}
}
else {scwID('scwFoot').style.display = 'none';}
if (scwDateValue.length==0)
{// If no value is entered and today is within the range,
// use today's date, otherwise use the middle of the valid range.
scwBlnFullInputDate=false;
if ((new Date(scwBaseYear+scwDropDownYears,0,0))<scwSeedDate ||
(new Date(scwBaseYear,0,1)) >scwSeedDate
)
{scwSeedDate = new Date(scwBaseYear + Math.floor(scwDropDownYears / 2), 5, 1);}
}
else
{function scwInputFormat()
{var scwArrSeed = new Array(),
scwArrInput = scwDateValue.split(new RegExp('[\\'+scwArrDelimiters.join('\\')+']+','g'));
// "Escape" all the user defined date delimiters above -
// several delimiters will need it and it does no harm for
// the others.
// Strip any empty array elements (caused by delimiters)
// from the beginning or end of the array. They will
// still appear in the output string if in the output
// format.
if (scwArrInput[0]!=null)
{if (scwArrInput[0].length==0) {scwArrInput.splice(0,1);}
if (scwArrInput[scwArrInput.length-1].length==0) {scwArrInput.splice(scwArrInput.length-1,1);}
}
scwBlnFullInputDate = false;
scwDateOutputFormat = scwDateOutputFormat.toUpperCase();
// List all the allowed letters in the date format
var template = ['D','M','Y'];
// Prepare the sequence of date input elements
var result = new Array();
for (var i=0;i<template.length;i++)
{if (scwDateOutputFormat.search(template[i])>-1)
{result[scwDateOutputFormat.search(template[i])] = template[i];}
}
var scwDateSequence = result.join('');
// Separate the elements of the date input
switch (scwArrInput.length)
{case 1:
{if (scwDateOutputFormat.indexOf('Y')>-1 &&
scwArrInput[0].length>scwDateOutputFormat.lastIndexOf('Y'))
{scwArrSeed[0] = parseInt(scwArrInput[0].substring(scwDateOutputFormat.indexOf('Y'),
scwDateOutputFormat.lastIndexOf('Y')+1),10);
}
else {scwArrSeed[0] = 0;}
if (scwDateOutputFormat.indexOf('M')>-1 &&
scwArrInput[0].length>scwDateOutputFormat.lastIndexOf('M'))
{scwArrSeed[1] = scwArrInput[0].substring(scwDateOutputFormat.indexOf('M'),
scwDateOutputFormat.lastIndexOf('M')+1);
}
else {scwArrSeed[1] = '6';}
if (scwDateOutputFormat.indexOf('D')>-1 &&
scwArrInput[0].length>scwDateOutputFormat.lastIndexOf('D'))
{scwArrSeed[2] = parseInt(scwArrInput[0].substring(scwDateOutputFormat.indexOf('D'),
scwDateOutputFormat.lastIndexOf('D')+1),10);
}
else {scwArrSeed[2] = 1;}
if (scwArrInput[0].length==scwDateOutputFormat.length) {scwBlnFullInputDate = true;}
break;
}
case 2:
{// Year and Month entry
scwArrSeed[0] =
parseInt(scwArrInput[scwDateSequence.
replace(/D/i,'').
search(/Y/i)],10); // Year
scwArrSeed[1] = scwArrInput[scwDateSequence.
replace(/D/i,'').
search(/M/i)]; // Month
scwArrSeed[2] = 1; // Day
break;
}
case 3:
{// Day Month and Year entry
scwArrSeed[0] =
parseInt(scwArrInput[scwDateSequence.
search(/Y/i)],10); // Year
scwArrSeed[1] = scwArrInput[scwDateSequence.
search(/M/i)]; // Month
scwArrSeed[2] =
parseInt(scwArrInput[scwDateSequence.
search(/D/i)],10); // Day
scwBlnFullInputDate = true;
break;
}
default:
{// A stuff-up has led to more than three elements in
// the date.
scwArrSeed[0] = 0; // Year
scwArrSeed[1] = 0; // Month
scwArrSeed[2] = 0; // Day
}
}
// These regular expressions validate the input date format
// to the following rules;
// Day 1-31 (optional zero on single digits)
// Month 1-12 (optional zero on single digits)
// or case insensitive name
// Year One, Two or four digits
// Months names are as set in the language-dependent
// definitions and delimiters are set just below there
var scwExpValDay = new RegExp('^(0?[1-9]|[1-2][0-9]|3[0-1])$'),
scwExpValMonth = new RegExp('^(0?[1-9]|1[0-2]|' +
scwArrMonthNames.join('|') +
')$','i'),
scwExpValYear = new RegExp('^([0-9]{1,2}|[0-9]{4})$');
// Apply validation and report failures
if (scwExpValYear.exec(scwArrSeed[0]) == null ||
scwExpValMonth.exec(scwArrSeed[1]) == null ||
scwExpValDay.exec(scwArrSeed[2]) == null
)
{if (scwShowInvalidDateMsg)
{alert(scwInvalidDateMsg +
scwInvalidAlert[0] + scwDateValue +
scwInvalidAlert[1]);}
scwBlnFullInputDate = false;
scwArrSeed[0] = scwBaseYear +
Math.floor(scwDropDownYears/2); // Year
scwArrSeed[1] = '6'; // Month
scwArrSeed[2] = 1; // Day
}
// Return the Year in scwArrSeed[0]
// Month in scwArrSeed[1]
// Day in scwArrSeed[2]
return scwArrSeed;
};
// Parse the string into an array using the allowed delimiters
scwArrSeedDate = scwInputFormat();
// So now we have the Year, Month and Day in an array.
// If the year is one or two digits then the routine assumes a
// year belongs in the 21st Century unless it is less than 50
// in which case it assumes the 20th Century is intended.
if (scwArrSeedDate[0]<100) {scwArrSeedDate[0] += (scwArrSeedDate[0]>50)?1900:2000;}
// Check whether the month is in digits or an abbreviation
if (scwArrSeedDate[1].search(/\d+/)<0)
{for (i=0;i<scwArrMonthNames.length;i++)
{if (scwArrSeedDate[1].toUpperCase()==scwArrMonthNames[i].toUpperCase())
{scwArrSeedDate[1]=i+1;
break;
}
}
}
scwSeedDate = new Date(scwArrSeedDate[0],scwArrSeedDate[1]-1,scwArrSeedDate[2]);
}
// Test that we have arrived at a valid date
if (isNaN(scwSeedDate))
{if (scwShowInvalidDateMsg) {alert(scwInvalidDateMsg + scwInvalidAlert[0] + scwDateValue + scwInvalidAlert[1]);}
scwSeedDate = new Date(scwBaseYear + Math.floor(scwDropDownYears/2),5,1);
scwBlnFullInputDate=false;
}
else
{// Test that the date is within range,
// if not then set date to a sensible date in range.
if ((new Date(scwBaseYear,0,1)) > scwSeedDate)
{if (scwBlnStrict && scwShowOutOfRangeMsg) {alert(scwOutOfRangeMsg);}
scwSeedDate = new Date(scwBaseYear,0,1);
scwBlnFullInputDate=false;
}
else
{if ((new Date(scwBaseYear+scwDropDownYears,0,0))<scwSeedDate)
{if (scwBlnStrict && scwShowOutOfRangeMsg) {alert(scwOutOfRangeMsg);}
scwSeedDate = new Date(scwBaseYear + Math.floor(scwDropDownYears)-1,11,1);
scwBlnFullInputDate=false;
}
else
{if (scwBlnStrict && scwBlnFullInputDate &&
(scwSeedDate.getDate() != scwArrSeedDate[2] ||
(scwSeedDate.getMonth()+1) != scwArrSeedDate[1] ||
scwSeedDate.getFullYear() != scwArrSeedDate[0]
)
)
{if (scwShowDoesNotExistMsg) alert(scwDoesNotExistMsg);
scwSeedDate = new Date(scwSeedDate.getFullYear(),scwSeedDate.getMonth()-1,1);
scwBlnFullInputDate=false;
}
}
}
}
// Test the disabled dates for validity
// Give error message if not valid.
for (var i=0;i<scwDisabledDates.length;i++)
{if (!((typeof scwDisabledDates[i] == 'object') && (scwDisabledDates[i].constructor == Date)))
{if ((typeof scwDisabledDates[i] == 'object') && (scwDisabledDates[i].constructor == Array))
{var scwPass = true;
if (scwDisabledDates[i].length !=2)
{if (scwShowRangeDisablingError)
{alert(scwRangeDisablingError[0] + scwDisabledDates[i] + scwRangeDisablingError[1]);}
scwPass = false;
}
else
{for (var j=0;j<scwDisabledDates[i].length;j++)
{if (!((typeof scwDisabledDates[i][j] == 'object') && (scwDisabledDates[i][j].constructor == Date)))
{if (scwShowRangeDisablingError)
{alert( scwDateDisablingError[0] + scwDisabledDates[i][j] + scwDateDisablingError[1]);}
scwPass = false;
}
}
}
if (scwPass && (scwDisabledDates[i][0] > scwDisabledDates[i][1])) {scwDisabledDates[i].reverse();}
}
else
{if (scwShowRangeDisablingError) {alert(scwDateDisablingError[0] + scwDisabledDates[i] + scwDateDisablingError[1]);}}
}
}
// Calculate the number of months that the entered (or
// defaulted) month is after the start of the allowed
// date range.
scwMonthSum = 12*(scwSeedDate.getFullYear()-scwBaseYear)+scwSeedDate.getMonth();
scwID('scwYears' ).options.selectedIndex = Math.floor(scwMonthSum/12);
scwID('scwMonths').options.selectedIndex = (scwMonthSum%12);
// Check whether or not dragging is allowed and display drag handle if necessary
scwID('scwDrag').style.display=(scwAllowDrag)?'':'none';
// Display the month
scwShowMonth(0);
// Position the calendar box
// The object sniffing for Opera allows for the fact that Opera
// is the only major browser that correctly reports the position
// of an element in a scrollable DIV. This is because IE and
// Firefox omit the DIV from the offsetParent tree.
scwTargetEle=scwEle;
var offsetTop =parseInt(scwEle.offsetTop ,10) + parseInt(scwEle.offsetHeight,10),
offsetLeft=parseInt(scwEle.offsetLeft,10);
if (!window.opera)
{while (scwEle.tagName!='BODY' && scwEle.tagName!='HTML')
{offsetTop -=parseInt(scwEle.scrollTop, 10);
offsetLeft-=parseInt(scwEle.scrollLeft,10);
scwEle=scwEle.parentNode;
}
scwEle=scwTargetEle;
}
do {scwEle=scwEle.offsetParent;
offsetTop +=parseInt(scwEle.offsetTop, 10);
offsetLeft+=parseInt(scwEle.offsetLeft,10);
}
while (scwEle.tagName!='BODY' && scwEle.tagName!='HTML');
if (scwAutoPosition)
{var scwWidth = parseInt(scwID('scw').offsetWidth, 10),
scwHeight = parseInt(scwID('scw').offsetHeight,10),
scwWindowLeft =
(document.body && document.body.scrollLeft)
?document.body.scrollLeft //DOM compliant
:(document.documentElement && document.documentElement.scrollLeft)
?document.documentElement.scrollLeft //IE6+ standards compliant
:0, //Failed
scwWindowWidth =
(typeof(innerWidth) == 'number')
?innerWidth //DOM compliant
:(document.documentElement && document.documentElement.clientWidth)
?document.documentElement.clientWidth //IE6+ standards compliant
:(document.body && document.body.clientWidth)
?document.body.clientWidth //IE non-compliant
:0, //Failed
scwWindowTop =
(document.body && document.body.scrollTop)
?document.body.scrollTop //DOM compliant
:(document.documentElement && document.documentElement.scrollTop)
?document.documentElement.scrollTop //IE6+ standards compliant
:0, //Failed
scwWindowHeight =
(typeof(innerHeight) == 'number')
?innerHeight //DOM compliant
:(document.documentElement && document.documentElement.clientHeight)
?document.documentElement.clientHeight //IE6+ standards compliant
:(document.body && document.body.clientHeight)
?document.body.clientHeight //IE non-compliant
:0; //Failed
offsetLeft -= (offsetLeft - scwWidth + parseInt(scwTargetEle.offsetWidth,10) >= scwWindowLeft &&
offsetLeft + scwWidth > scwWindowLeft + scwWindowWidth
)?(scwWidth - parseInt(scwTargetEle.offsetWidth,10)):0;
offsetTop -= (offsetTop - scwHeight - parseInt(scwTargetEle.offsetHeight,10) >= scwWindowTop &&
offsetTop + scwHeight > scwWindowTop + scwWindowHeight
)?(scwHeight + parseInt(scwTargetEle.offsetHeight,10)):0;
}
scwID('scw').style.top = offsetTop+'px';
scwID('scw').style.left = offsetLeft+'px';
scwID('scwIframe').style.top = offsetTop+'px';
scwID('scwIframe').style.left = offsetLeft+'px';
scwID('scwIframe').style.width =(scwID('scw').offsetWidth-(scwID('scwIE')?2:4))+'px';
scwID('scwIframe').style.height=(scwID('scw').offsetHeight-(scwID('scwIE')?2:4))+'px';
scwID('scwIframe').style.visibility='inherit';
// Show it on the page
scwID('scw').style.visibility='inherit';
};

Change text depending on the time of day and on which button is clicked

I need to display different text 'set' depending on which button I click, and rotate messages in this 'set' depending on what time it is.
This is what I've got:
var date = new Date;
var hh = date.getHours();
var mm = date.getMinutes();
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
var t = hh+":"+mm;
var themessage;
function TimeF() {
if (check == "alt") {
if (t >= "08:00" && t <= "09:00"){
themessage = "A";
}
else if(t >= "09:05" && t <= "10:05"){
themessage = 2;
}
}
else if (check == "NoPack") {
if (t >= "08:00" && t <= "09:14"){
themessage = "NP";
}
else if(t >= "09:19" && t <= "10:33"){
themessage = 2;
}
}
else if (check == "pack") {
if (t >= "08:00" && t <= "09:14") {
themessage = "pack";
}
}
else if (n == 3) {
if (t >= "08:00" && t <= "09:14"){
themessage = "n=3";
}
else if(t >= "09:19" && t <= "10:33"){
themessage = 2;
}
}
else {
if (t >= "08:00" && t <= "09:19") {
themessage = "Else";
}
else if (t >= "09:21" && t<= "10:43"){
themessage =2;
}
}
$('.Test').append(themessage);
}
Also I have button code:
var reg = document.getElementById("Reg");
var pack = document.getElementById("Pack");
var nopack = document.getElementById("NoPack");
var alt = document.getElementById("Alt");
var sch = document.getElementById("Sch");
var check;
var update;
$(document).ready(function () {
$("#Pack").click(function () {
$("#Sch").html("pack");
check = "pack";
});
$("#Reg").click(function () {
$("#Sch").html("Reg");
check = "reg";
});
$("#NoPack").click(function () {
$("#Sch").html("NoPack");
check = "NoPack";
});
$("#Alt").click(function () {
$("#Sch").html("Alternate");
check = "alt";
});
})
The problem is - when I press any button, the code shows the text for 'esle', and not what I supposed to be assigned to that button.
P.S I have jquery refference and I am loading this function TimeF in body.
If you want, I could make a quick CodePen with this.
P.S.S n==3 in my code - is checking if it is Wednesday.

Birthdate Validation in JavaScript

I'm trying to validate a Birthday date but I can only validate if all filled in.
If I just choose date, there is no alert ("day must be chosen / month must be chosen").
I can't validate a date...
How to run this validation?
function isbday(day,month,year) {
var mth = month;
var dy = day;
var yr = year;
if((mth < 1) || (mth > 12));
else if((dy < 1) || (dy > 31));
else if(((mth == 4) || (mth == 6) || (mth == 9) || (mth == 11)) && (dy > 30));
else if((mth == 2) && (((yr % 400) == 0) || ((yr % 4) == 0)) && ((yr % 100) != 0) && (day > 29));
else if((mth == 2) && ((yr % 100) == 0) && (dy > 29));
else if((mth == 2) && (dy > 28)) valid = false;
return false;
alert("Birthdate must be filled");
}
function validate(){
var day = document.getElementsByName("xday")[0].value;
var month = document.getElementsByName("xmonth")[0].value;
var year = document.getElementsByName("xyear")[0].value;
if(day,month,year == null || day,month,year == ""){
alert("Birthdate must be filled");
}else if(birthdate.match(isbday(birthdate))){
alert("Birthdate must be filled");
}else
{
alert("Birthdate success");
}
}
<tr>
<td >Birthdate </td>
<td><select name="xday">
<option value="">Date</option>
<script>
var myDate = new Date();
var year = myDate.getFullYear();
for(var i = 1; i < 32; i++){
document.write('<option value="'+i+'">'+i+'</option>');
}
</script>
</select>
<select name="xmonth">
<option value="">Month</option>
<script>
var myDate = new Date();
var year = myDate.getFullYear();
for(var i = 1; i < 13; i++){
document.write('<option value="'+i+'">'+i+'</option>');
}
</script>
</select>
<select name="xyear">
<option value="">Year</option>
<script>
var myDate = new Date();
var year = myDate.getFullYear();
for(var i = 1950; i < year; i++){
document.write('<option value="'+i+'">'+i+'</option>');
}
</script>
</select>
</td>
</tr>
<tr>
<td>
<input type="button" name="btnRegis" onClick="validate()" onsub value="Register"/>
</td>
</tr>
I think the best way is to change the day select according to the month that was selected but if you still want to do it the same way:
Change a little bit your valid function
Each if statement return false if not valid
function isVaild(day, month, year) {
var mth = month;
var dy = day;
var yr = year;
//Checks
if ((mth < 1) || (mth > 12)) return false;
else if ((dy < 1) || (dy > 31)) return false;
else if (((mth == 4) || (mth == 6) || (mth == 9) || (mth == 11)) && (dy > 30)) return false;
else if ((mth == 2) && (((yr % 400) == 0) || ((yr % 4) == 0)) && ((yr % 100) != 0) && (day > 29)) return false;
else if ((mth == 2) && ((yr % 100) == 0) && (dy > 29)) return false;
else if ((mth == 2) && (dy > 28)) return false;
//Pass all checks
return true;
}
function validate() {
var day = document.getElementsByName("xday")[0].value;
var month = document.getElementsByName("xmonth")[0].value;
var year = document.getElementsByName("xyear")[0].value;
//if one is empty
if (day, month, year === null || day, month, year === "") {
alert("Birthdate must be filled\nDay, Month, Year is empty");
}
//if not a vaild date
else if (!isVaild(day, month, year)) {
alert("Birthdate not vaild");
}
//All good :)
else {
alert("Birthdate success");
}
}
Working example here

Categories

Resources