input 0 is not defined stack:reference error - javascript

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';
};

Related

Angularjs tiny display bug with ng-if

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;
};
});
})();

Check and alert for the null value

I need to check for the null values and alert them if there are any before getting saved. I have used this code but I am not able to alert the null values instead it is getting saved . .
function fn_publish() {
var SessionNames = getParameterByName('SessionName');
var MenuType = getParameterByName('MenuType');
var Date = getParameterByName('ForDate');
var publish = "Y";
Dates = Date.split("-");
Date = Dates[1] + "/" + Dates[2] + "/" + Dates[0];
var rows = [];
cols = document.getElementById('product_table').rows[1].cells.length - 1;
table = document.getElementById('product_table');
for (var i = 1; i <= cols; i++) {
for (var j = 0, row; row = table.rows[j]; j++) {
if (j == 0) {
cust = row.cells[i].innerText;
alert(cust);
} else if (j == 1) {
catlg = row.cells[i].innerText;
alert(catlg);
} else {
if (typeof (row.cells[i]) != "undefined") {
if (row.cells[i].innerText != "") {
//alert(SessionNames+"::"+MenuType+"::"+Date+"::"+catlg+"::"+row.cells[0].innerText+"::"+row.cells[i].innerText+"::"+cust+"::"+publish);
fn_insert(SessionNames, MenuType, Date, catlg, row.cells[0].innerText, row.cells[i].innerText, cust, publish);
} else {
jAlert("Please select a product", "ok");
return false;
}
}
}
}
}
jAlert("Menu Published", "ok");
}
if (row.cells[i].innerText != "") {
May be the cells are containing empty space in that. Better trim ad then compare.
if (row.cells[i].innerText.trim() !== "") {
Also instead of innerText use textContent which is common in most modern browsers.
if (row.cells[i].textContent.trim() !== "") {

onClick of javascript not working in Browser like chrome,firefox

Sir,
I have Javascript calendar(for Picking a date) downloaded from Internet. i am able to pick a appropriate Date when working in IE 6 version. But it is unable to pick a date(on click not working) when I am using Modern Browser like Google chrome. here is code Snippet. Advice Kindly!
calendar.js file
monthMaxDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
monthMaxDaysLeap= [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
hideSelectTags = [];
function getRealYear(dateObj)
{
return (dateObj.getYear() % 100) +
(((dateObj.getYear() % 100) < 39) ? 2000 : 1900);
}
function getDaysPerMonth(month, year)
{
/*
Check for leap year. These are some conditions to check
year is leap year or not...
1.Years evenly divisible by four are normally leap years, except for...
2.Years also evenly divisible by 100 are not leap years, except for...
3.Years also evenly divisible by 400 are leap years.
*/
if ((year % 4) == 0)
{
if ((year % 100) == 0 && (year % 400) != 0)
return monthMaxDays[month];
return monthMaxDaysLeap[month];
}
else
return monthMaxDays[month];
}
function createCalender(year, month, day)
{
// current Date
var curDate = new Date();
var curDay = curDate.getDate();
var curMonth = curDate.getMonth();
var curYear = getRealYear(curDate)
// if a date already exists, we calculate some values here
if (!year)
{
var year = curYear;
var month = curMonth;
}
var yearFound = 0;
for (var i=0; i<document.getElementById('selectYear').options.length; i++)
{
if (document.getElementById('selectYear').options[i].value == year)
{
document.getElementById('selectYear').selectedIndex = i;
yearFound = true;
break;
}
}
if (!yearFound)
{
document.getElementById('selectYear').selectedIndex = 0;
year = document.getElementById('selectYear').options[0].value;
}
document.getElementById('selectMonth').selectedIndex = month;
// first day of the month.
var fristDayOfMonthObj = new Date(year, month, 1);
var firstDayOfMonth = fristDayOfMonthObj.getDay();
continu = true;
firstRow = true;
var x = 0;
var d = 0;
var trs = []
var ti = 0;
while (d <= getDaysPerMonth(month, year))
{
if (firstRow)
{
trs[ti] = document.createElement("TR");
if (firstDayOfMonth > 0)
{
while (x < firstDayOfMonth)
{
trs[ti].appendChild
(document.createElement ("TD"));
x++;
}
}
firstRow = false;
var d = 1;
}
if (x % 7 == 0)
{
ti++;
trs[ti] = document.createElement("TR");
}
if ( day && d == day)
{
var setID = 'calenderChoosenDay';
var styleClass = 'choosenDay';
var setTitle = 'this day is currently selected';
}
else if (d == curDay && month == curMonth && year == curYear)
{
var setID = 'calenderToDay';
var styleClass = 'toDay';
var setTitle = 'this day today';
}
else
{
var setID = false;
var styleClass = 'normalDay';
var setTitle = false;
}
var td = document.createElement("TD");
td.className = styleClass;
if (setID)
{
td.id = setID;
}
if (setTitle)
{
td.title = setTitle;
}
td.onmouseover = new Function('highLiteDay(this)');
td.onmouseout = new Function('deHighLiteDay(this)');
*if (targetEl)
td.onclick = new Functio*
('pickDate ('+year+', '+month+', '+d+')');
else
td.style.cursor = 'default';
td.appendChild(document.createTextNode(d));
trs[ti].appendChild(td);
x++;
d++;
}
return trs;
}
function showCalender(elPos, tgtEl)
{
targetEl = false;
if (document.getElementById(tgtEl))
{
targetEl = document.getElementById(tgtEl);
}
else
{
if (document.forms[0].elements[tgtEl])
{
targetEl = document.forms[0].elements[tgtEl];
}
}
var calTable = document.getElementById('calenderTable');
var positions = [0,0];
var positions = getParentOffset(elPos, positions);
calTable.style.left = positions[0]+'px';
calTable.style.top = positions[1]+'px';
calTable.style.display='block';
var matchDate = new RegExp('^([0-9]{2})-([0-9]{2})-([0-9]{4})$');
var m = matchDate.exec(targetEl.value);
if (m == null)
{
trs = createCalender(false, false, false);
showCalenderBody(trs);
}
else
{
if (m[1].substr(0, 1) == 0)
m[1] = m[1].substr(1, 1);
if (m[2].substr(0, 1) == 0)
m[2] = m[2].substr(1, 1);
m[2] = m[2] - 1;
trs = createCalender(m[3], m[2], m[1]);
showCalenderBody(trs);
}
hideSelect(document.body, 1);
}
function showCalenderBody(trs)
{
var calTBody = document.getElementById('calender');
while (calTBody.childNodes[0])
{
calTBody.removeChild(calTBody.childNodes[0]);
}
for (var i in trs)
{
calTBody.appendChild(trs[i]);
}
}
function setYears(sy, ey)
{
// current Date
var curDate = new Date();
var curYear = getRealYear(curDate);
if (sy)
startYear = curYear;
if (ey)
endYear = curYear;
document.getElementById('selectYear').options.length = 0;
var j = 0;
for (y=ey; y>=sy; y--)
{
document.getElementById('selectYear')[j++] = new Option(y, y);
}
}
function hideSelect(el, superTotal)
{
if (superTotal >= 100)
{
return;
}
var totalChilds = el.childNodes.length;
for (var c=0; c<totalChilds; c++)
{
var thisTag = el.childNodes[c];
if (thisTag.tagName == 'SELECT')
{
if (thisTag.id != 'selectMonth' && thisTag.id != 'selectYear')
{
var calenderEl = document.getElementById ('calenderTable');
var positions = [0,0];
var positions = getParentOffset(thisTag, positions); // nieuw
var thisLeft = positions[0];
var thisRight = positions[0] + thisTag.offsetWidth;
var thisTop = positions[1];
var thisBottom = positions[1] + thisTag.offsetHeight;
var calLeft = calenderEl.offsetLeft;
var calRight = calenderEl.offsetLeft + calenderEl.offsetWidth;
var calTop = calenderEl.offsetTop;
var calBottom = calenderEl.offsetTop + calenderEl.offsetHeight;
if (
(
/* check if it overlaps horizontally */
(thisLeft >= calLeft && thisLeft <= calRight)
||
(thisRight <= calRight && thisRight >= calLeft)
||
(thisLeft <= calLeft && thisRight >= calRight)
)
&&
(
/* check if it overlaps vertically */
(thisTop >= calTop && thisTop <= calBottom)
||
(thisBottom <= calBottom && thisBottom >= calTop)
||
(thisTop <= calTop && thisBottom >= calBottom)
)
)
{
hideSelectTags[hideSelectTags.length] = thisTag;
thisTag.style.display = 'none';
}
}
}
else if(thisTag.childNodes.length > 0)
{
hideSelect(thisTag, (superTotal+1));
}
}
}
function closeCalender()
{
for (var i=0; i<hideSelectTags.length; i++)
{
hideSelectTags[i].style.display = 'block';
}
hideSelectTags.length = 0;
document.getElementById('calenderTable').style.display='none';
}
function highLiteDay(el)
{
el.className = 'hlDay';
}
function deHighLiteDay(el)
{
if (el.id == 'calenderToDay')
el.className = 'toDay';
else if (el.id == 'calenderChoosenDay')
el.className = 'choosenDay';
else
el.className = 'normalDay';
}
function pickDate(year, month, day)
{
month++;
day = day < 10 ? '0'+day : day;
month = month < 10 ? '0'+month : month;
if (!targetEl)
{
alert('target for date is not set yet');
}
else
{
targetEl.value= year+'-'+month+'-'+day;
closeCalender();
}
}
function getParentOffset(el, positions)
{
positions[0] += el.offsetLeft;
positions[1] += el.offsetTop;
if (el.offsetParent)
positions = getParentOffset(el.offsetParent, positions);
return positions;
}
Wow, new Function()? Really?
td.onmouseover = function() {highLiteDay(this);};
td.onmouseout = function() {deHighLiteDay(this);};
// the above two should probably just be `:hover` styles in CSS
(function(year,month,d) {
td.onclick = function() {pickDate(year, month, d);};
})(year,month,d);
// this creates a closure to "anchor" the values of the variables
// even as the loop iterates

Why my date and month is getting swaped if the date is lesser than 12?

Problem
If I am selecting lesser than 12 date then it display in this format MM/D/YYYY and if the date is greater than 12 then output comes as DD/M/YYYY. I want to get this format DD/M/YYYY whatever the user select. I am also using protoype.js with it. Any help will be much appreciated.
Code
var Recurrence = Class.create({
// takes a JSON object with pattern options
initialize: function (pattern, date_format) {
if (typeof pattern != 'object') throw new TypeError('pattern must be a JSON');
if (!pattern.every || pattern.every.blank()) {
throw new ReferenceError('Every magnitude must be specified');
}
if (isNaN(parseInt(pattern.every))) {
throw new TypeError('Every magnitude must be a valid number');
}
// stores generated dates based on recurrence pattern
this.dates = [];
this.start = Date.parse(pattern.start);
this.every = parseInt(pattern.every);
this.unit = pattern.unit;
this.end_condition = pattern.end_condition;
this.until = Date.parse(pattern.until);
this.rfor = parseInt(pattern.rfor);
this.occurrence_of = pattern.occurrence_of;
this.nth = parseInt(pattern.nth);
this.radioSelection = pattern.radioSelection;
this.indefinate = Date.parse(pattern.indefinate);
this.days = (pattern.days) ? pattern.days.sort() : [];
this.date_format = date_format || 'dd/M/yyyy';
this.month_date_format = date_format || 'dd';
},
// tries to describe the pattern in plain english
describe: function () {
var units = {'d': 'day', 'w': 'week', 'm': 'month', 'y': 'year'};
var week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'day'];
var nthword = ['', 'first', 'second', 'third', 'fourth', 'fifth', 'last']
var t = ['Every'];
if (this.every > 2) {
t.push(this.every, units[this.unit] + 's');
} else if (this.every == 2) {
t.push('other', units[this.unit]);
} else {
t.push(units[this.unit]);
}
//alert(this.radioSelection);
//alert(this.end_condition);
if (this.unit == 'w') {
var d = [];
for (var i = 0; i < this.days.length; i++) {
d.push(week[this.days[i]]);
}
t.push('on', d.join(', '));
} else if (this.unit == 'm') {
// check if it's a special word
day_idx = (this.occurrence_of < 0) ? week.length - 1 : this.occurrence_of;
nth_idx = (this.nth < 0) ? nthword.length-1 : this.nth;
//alert(this.radioSelection);
if(this.radioSelection == 'weekday'){
t.push('on the', nthword[nth_idx], week[day_idx]);
}else{
t.push('on date ', this.start.toString(this.month_date_format));
}//end if..
}
t.push('starting on', this.start.toString(this.date_format));
if (this.end_condition == 'until') {
t.push('until', this.until.toString(this.date_format));
} else if (this.end_condition == 'for') {
t.push('for', this.rfor, 'occurrences');
} else if(this.end_condition == 'indefinate'){
t.push('ends never.');//alert('sds');
}
return t.join(' ');
},
// determine whether given date is in recurrence
contains: function (d) {
if (this.dates.length == 0) this.generate();
// can be string or date object already
d = Date.parse(d);
for (var i = 0; i < this.dates.length; i++) {
if (Date.equals(this.dates[i], d)) return true;
}
return false;
},
// returns an array of dates base on input pattern
generate: function (max) {
if (!(this.rfor || this.until || max)) {
throw new RangeError('There is no valid end condition specified');
}
var end_condition_reached = function (occurrences, current_date) {
if (max && occurrences.length >= max) return true;
if (this.end_condition == 'for' && this.rfor && occurrences.length >= this.rfor) return true;
if (this.end_condition == 'until' && this.until && current_date > this.until) return true;
if (this.end_condition == 'indefinate' && this.indefinate && current_date > this.indefinate) return true;
return false;
}.bind(this);
var dates = [];
var curr = this.start.clone().clearTime();
// always include start date in recurrence
dates.push(curr.clone());
// weekly recurrence
if (this.unit == 'w') {
// if it's not already a sunday, move it to the current week's sunday
if (!curr.is().sunday()) curr.last().sunday();
if (this.days.length == 0) {
throw new RangeError('Weekly recurrence was selected without any days specified.');
return null;
}
while (!end_condition_reached(dates, curr)) {
// scan through the checked days
this.days.each(function (d) {
if (curr.getDay() < d) curr.moveToDayOfWeek(d);
if (curr <= this.start) return;
if (end_condition_reached(dates, curr)) return;
dates.push(curr.clone());
}.bind(this));
// rewind back to sunday
if (!curr.is().sunday()) curr.last().sunday();
// next repetition
curr.addWeeks(this.every);
}
} else if (this.unit == 'm') {
while (true) {
if (this.occurrence_of == -1) {
curr.moveToLastDayOfMonth();
} else {
if(this.radioSelection == 'weekday'){
curr.moveToNthOccurrence(this.occurrence_of, this.nth);
}else{
//this.occurrence_of = this.faltu_date;
}//end if
}//end if..
if (end_condition_reached(dates, curr)) break;
if (curr > this.start) {
dates.push(curr.clone());
}//end if..
curr.addMonths(this.every);
}//end while..
} else {
while (true) {
if (this.unit == 'd') {
curr.addDays(this.every);
} else if (this.unit == 'y') {
curr.addYears(this.every);
}
// else infinite loop yay
if (end_condition_reached(dates, curr)) break;
dates.push(curr.clone());
}
}
// cache results
this.dates = dates;
return this.dates;
}
});

How to select line of text in textarea

I have a textarea that is used to hold massive SQL scripts for parsing. When the user clicks the "Parse" button, they get summary information on the SQL script.
I'd like the summary information to be clickable so that when it's clicked, the line of the SQL script is highlighted in the textarea.
I already have the line number in the output so all I need is the javascript or jquery that tells it which line of the textarea to highlight.
Is there some type of "goToLine" function? In all my searching, nothing quite addresses what I'm looking for.
This function expects first parameter to be reference to your textarea and second parameter to be the line number
function selectTextareaLine(tarea,lineNum) {
lineNum--; // array starts at 0
var lines = tarea.value.split("\n");
// calculate start/end
var startPos = 0, endPos = tarea.value.length;
for(var x = 0; x < lines.length; x++) {
if(x == lineNum) {
break;
}
startPos += (lines[x].length+1);
}
var endPos = lines[lineNum].length+startPos;
// do selection
// Chrome / Firefox
if(typeof(tarea.selectionStart) != "undefined") {
tarea.focus();
tarea.selectionStart = startPos;
tarea.selectionEnd = endPos;
return true;
}
// IE
if (document.selection && document.selection.createRange) {
tarea.focus();
tarea.select();
var range = document.selection.createRange();
range.collapse(true);
range.moveEnd("character", endPos);
range.moveStart("character", startPos);
range.select();
return true;
}
return false;
}
Usage:
var tarea = document.getElementById('myTextarea');
selectTextareaLine(tarea,3); // selects line 3
Working example:
http://jsfiddle.net/5enfp/
A somewhat neater version of the search for lines:
function select_textarea_line (ta, line_index) {
const newlines = [-1]; // Index of imaginary \n before first line
for (let i = 0; i < ta.value.length; ++i) {
if (ta.value[i] == '\n') newlines.push( i );
}
ta.focus();
ta.selectionStart = newlines[line_index] + 1;
ta.selectionEnd = newlines[line_index + 1];
} // select_textarea_line
Add a onclick or ondblclick event handler to your <textarea>:
<textarea onclick="onClickSelectLine(this)"></textarea>
And JavaScript function to handle the onclick event:
/**
* onclick event for TextArea to select the whole line
* #param textarea {HTMLTextAreaElement}
* #returns {boolean}
*/
function onClickSelectLine(textarea) {
if (typeof textarea.selectionStart == 'undefined') {
return false
}
let text = textarea.value
let before = text.substring(0, textarea.selectionStart)
let after = text.substring(textarea.selectionEnd, text.length);
let startPos = before.lastIndexOf("\n") >= 0 ? before.lastIndexOf("\n") + 1 : 0
let endPos = after.indexOf("\n") >= 0 ? textarea.selectionEnd + after.indexOf("\n") : text.length
textarea.selectionStart = startPos
textarea.selectionEnd = endPos
return true
}
To make the function more forgiving on possible faulty input add after:
// array starts at 0
lineNum--;
This code:
if (typeof(tarea) !== 'object' || typeof(tarea.value) !== 'string') {
return false;
}
if (lineNum === 'undefined' || lineNum == null || lineNum < 0) {
lineNum = 0;
}
How to select line of text in textarea javascript double click on particular line.
//This function expects first parameter to be reference to your textarea.
function ondblClickSelection(textarea){
var startPos = 0;
var lineNumber = 0;
var content = "";
if(typeof textarea.selectionStart == 'undefined') {
return false;
}
startPos = textarea.selectionStart;
endPos = textarea.value.length;
lineNumber = textarea.value.substr(0,startPos).split("\n").length - 1;
content = textarea.value.split("\n")[lineNumber];
var lines = textarea.value.split("\n");
var endPos = lines[lineNumber].length+startPos;
textarea.selectionStart = startPos;
textarea.selectionEnd = endPos;
return true;
}

Categories

Resources