Uncaught rangeError : Invalid string length - javascript

so i have just started to learn javascript, literally had 2 classes on it. So my knowledge is very very limited. But I am trying to make an appointment application and i keep receiving a Uncaught rangeError :Invalid string length error, and i have no idea why or how to fix it. Basically I have been given some code to copy without much explanation to it, so if anyone can help me with this error it would be greatly appreciated. The code where the error is appearing is below and i believe it is the line table += appt.tableRow(); which is causing the issue. There is obviously more to this code, but not sure if it needs to be given, as the issue is in the showTable function
Edit : I just added the whole javascript code to make it easier
var Appointment = function(subject, description,date, time) {
this.subject = subject;
this.description = description;
this.datetime = new Date(date + " " + time);
this.completed = false;
};
Appointment.prototype.isDue = function(){
var now = new Date();
if(this.datetime > now){
return false;
} else {
return true;
}
};
Appointment.prototype.whenDue = function(){
return this.datetime - new Date();
}
Appointment.prototype.toString = function(){
var s = this.subject +'\n'+
this.datetime.toString() + '\n';
if(this.completed){
s +="Not Completed\n\n";
}
return s
};
Appointment.prototype.howManyDaysTill = function() {
var ms = (this.datetime - new Date()) / 24/60/60/1000
return ms;
};
Appointment.prototype.howManyHoursTill = function () {
var hours = (this.datetime - new Date()) /60/60/1000
return hours;
};
Appointment.prototype.getDate = function() {
return this.datetime.toDateString();
};
Appointment.prototype.getTime = function (){
return (this.datetime.getHours()) + ":" + (this.datetime.getMinutes());
};
Appointment.prototype.tableRow = function(){
var tr = "<tr><td>" + this.getDate() + "</td><td>" +
this.getTime() + "</td><td>" + this.subject +
"</td></tr>";
return tr;
};
var appointments = [];
window.onload = function(){
var newButton = document.getElementById("new");
newButton.onclick = function () {
var subj = prompt("Enter a subject title for the appointment");
var desc = prompt("Enter a description for the appointment");
var date = prompt("Enter the appointment date in the format (e.g) 'Sep
25, 2012");
var time = prompt("Enter the appointment time in the format hh:mm");
var a = new Appointment((subj,desc,date,time));
appointments.push(a);
return showTable();
};
var showTable = function() {
var tableDiv = document.getElementById("table"),
table = "<table border='1'>" +
"<thead><th>Date</th><th>Time</th><th>Subject</th><th>Completed</th>
</thead>";
for (var i = 0, j = appointments.length; i < j; j++) {
var appt = appointments[i];
table += appt.tableRow();
}
table += "</table>";
tableDiv.innerHTML = table;
};
}
HTML5
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="appointments.js"></script>
<title>Appointments</title>
</head>
<body>
<button id="new">New Appointment</button>
<div id ="table"></div>
<header>
<h1>
Appointments Book
</h1>
<p> Enter appointment details and press OK to add, Cancel to revert.</p>
</header>
<table>
<tr>
<td>Subject : </td> <td>input type="text" size="40" id="subject"</td>
</tr>
<tr>
<td>Description</td>
<td>
<textarea rows = "5" cols=""50" maxlength="200" id="description">
</textarea>
</td>
</tr>
<tr> <td>Due Date:</td><td><input type ="date" id="duedate"/></td>
</tr>
</table>
<button id = "OK">OK </button><button id = "cancel">Cancel</button>
<hr/>
</body>
</html>

The for loop must increment on i and not on j. The current one is causing a infinite looping and hence the following line is creating a string that is too big to handle by the JS engine and hence the error
table += appt.tableRow();

Related

Get all spreadsheet data to client side first, then "find row number and same row values using javascript for a specific value"

Code.js
/**
* Load Spreadsheet by ID
* Get all Sheets present in that spreadsheet
* Loop through each sheet
* Create an object with sheet's name as Key of the object
* and sheets data as Value of the object
* Return the key-value paired object
*/
function doGet(e) {
return HtmlService
.createHtmlOutputFromFile('form.html')
.setTitle("Exam Result");
}
function getAllResult()
{
var id = '1da6d8rfWgZrG2Cnpyho6YDx0C7Me4o20rM4PhDi8yCY'; // ID of the Result spreadsheet
var ss = SpreadsheetApp.openById(id);
var sheets = ss.getSheets(); // get all the sheets in the spreadsheeet
var allSheetsData = {}; // initialize javascript object
var sheetName = '';
var sheetValues;
for (i = 0; i < sheets.length; i++) {
sheetName = sheets[i].getName();
sheetValues = sheets[i].getDataRange().getValues();
allSheetsData[sheetName] = sheetValues;
}
//Logger.log(allSheetsData);
return allSheetsData;
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
window.onload = function() {
init(); // initial function to run on page load
};
// initializing object that will be storing all result data
var allResultData = {};
// loading image
var loading = '<img width="25px" ' +
'src="https://lh6.googleusercontent.com/PshQKOjKS5j6IEaEXZ6r7-JOFZwYOBopBt82Q-kTGdRcW6wi3SBHDAUHebb2yreOeTpGfzgs=w1280-h661"> ' +
'Loading...';
/**
* First function to run on page load
*/
function init() {
document.getElementById('progressClass').innerHTML = loading; // show loading image
/**
* This calls getAllResult() function of Code.gs
* The returned value from getAllResult() is passed to populateClass(value) function
* present in this html file
*/
google.script.run
.withSuccessHandler(populateClass)
.getAllResult();
}
/**
* Second function to run after init() function
* Populates the "Class" select box
*/
function populateClass(value) {
document.getElementById('progressClass').innerHTML = ''; // hide loading image
allResultData = value; // all result data is stored in allResultData object
var className = Object.keys(value);
var classes = '<option>Please Select</option>';
for (i = 0; i < className.length; i++) {
classes += "<option>" + className[i] + "</option>";
}
document.getElementById("class").innerHTML = classes;
}
function populateSymbolNumber(value)
{
{var day = "<option>Day</option>";
var data = allResultData[value]
for (i=1; i < 32; i++) { // start from i=1, skipping 1st row as it's heading
day += "<option value="+i+">" + data[i][3] + "</option>";
}
document.getElementById("day").innerHTML = day;}
{var month = "<option>Month</option>";
var data = allResultData[value]
for (i=1; i < 13; i++) { // start from i=1, skipping 1st row as it's heading
month += "<option value="+i+">" + data[i][4] + "</option>";
}
document.getElementById("month").innerHTML = month;}
{var year = "<option>Year</option>";
var data = allResultData[value]
for (i=1; i < 122; i++) { // start from i=1, skipping 1st row as it's heading
year += "<option value="+i+">" + data[i][5] + "</option>";
}
document.getElementById("year").innerHTML = year;}
{var symbol = "<option>Please Select</option>";
var data = allResultData[value]
for (i=1; i < data.length; i++) { // start from i=1, skipping 1st row as it's heading
symbol += "<option value="+i+">" + data[i][0] + "</option>";
}
document.getElementById("symbol").innerHTML = symbol;}
}
/**
* Show name of student and marks result
*/
function submitForm(value) {
var grade = document.getElementById("class");
var gradeValue = grade.options[grade.selectedIndex].value;
var classResult = allResultData[gradeValue];
var symbol = document.getElementById("symbol");
var day = document.getElementById("day");
var month = document.getElementById("month");
var year = document.getElementById("year");
var symbolText = symbol.options[symbol.selectedIndex].text;
var DayText = day.options[day.selectedIndex].text;
var MonthText = month.options[month.selectedIndex].text;
var YearText = year.options[year.selectedIndex].text;
var symbolValue = symbol.options[symbol.selectedIndex].value;
var dob = DayText + '-' + MonthText + '-' + YearText;
var marks = '';
var headerRow = classResult[0];
//console.log(headerRow);
for (i = 1; i < headerRow.length; i++) { // start from i=1, skipping 1st column as it contains symbol number
marks += headerRow[i] + ': ' + classResult[symbolValue][i] + '<br>';
}
var result = "Symbol Number: " + symbolText + '<br>' + marks;
document.getElementById('result').innerHTML = result;
return false;
}
</script>
</head>
<body>
<div id="form">
<table cellpadding="5px">
<tr>
<td>Class</td>
<td>
<select id="class" onchange="populateSymbolNumber(this.value)">
<option value="">Please Select</option>
</select>
<span id="progressClass"></span>
</td>
</tr>
<tr>
<td>Symbol</td>
<td>
<select id="day">
<option value="">Day</option>
</select>
</td>
<td>
<select id="month">
<option value="">Month</option>
</select>
</td>
<td>
<select id="year">
<option value="">Year</option>
</select>
</td>
<td>
<select id="symbol">
<option value="">Please Select</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td>
<button onclick="submitForm(); return false;">Submit</button>
</td>
</tr>
</table>
</div>
<div id="result" style="border-top: 1px solid #ccc; padding: 5px"></div>
</body>
</html>
There is a variable
var dob = DayText + '-' + MonthText + '-' + YearText;
I want to find row number for the "dob" value in the loaded data.
Google sheet has value as 30-December-1992.

AWS Javascript SDK EC2 DescribeInstances

I am trying to get date & no. of instances spin-up on that day.
Here is my code , i am beginner in development & in javascript.
so forgive me in advance for any immature code.
after getting startdate & end date , dates are stored in listDate array.
hours of a day is stored in hourArray.
then using JS SDK for AWS to get no. of instances spinned up on specific date.
ec2.describeInstances is not working as expected here ,
sometimes , i got output from ec2.describeInstances correctly , but it is always picking end date in all while loop iterations.
most of the time , ec2.describeInstances doesnt even execute.
function applyFilters() {
var listDate = [];
demo1.innerHTML = '';
var startDate = document.getElementById("fromdate").value;
var endDate = document.getElementById("todate").value;
//alert(startDate);
//alert(endDate);
var dateMove = new Date(startDate);
var strDate = startDate;
while (strDate < endDate){
var strDate = dateMove.toISOString().slice(0,10);
listDate.push(strDate);
dateMove.setDate(dateMove.getDate()+1);
};
//alert(listDate);
//document.getElementById('demo1').innerHTML = "Your selected dates are";
//demo2.innerHTML += "<br>";
//document.getElementById('demo3').innerHTML = listDate;
alert(listDate);
var i = 0;
var j = listDate.length;
alert(j);
while (i < j){
alert(i);
alert(listDate[i]);
var hourArray = [];
var d = listDate[i];
for (var h = 0; h <= 9; h++) {
hourArray.push(d + 'T' + '0' + h + '*');
}
for (var m = 10; m <= 23; m++) {
hourArray.push(d + 'T' + m + '*');
}
alert(hourArray);
var ec2 = new AWS.EC2();
AWS.config.update({
region: "xxxxxxx",
accessKeyId: "xxxxxxxxxxxxxxxxxxxxx",
secretAccessKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
});
i++;
var params = {
Filters: [
{
Name: 'launch-time',
Values: hourArray
}]
};
//alert("Specified launch-times are: " + hourArray);
ec2.describeInstances(params, function(err, data, d) {
//alert(data);
if (err) {
//demo5.innerHTML = 'ERROR:' + err;
console.log(err);
} else {
var no_of_inst = data.Reservations.length;
//demo4.innerHTML += "<br>";
//document.getElementById('demo5').innerHTML = 'Instances migrated on' + listdate[i] + 'are: ' + no_of_inst;
alert("Instances migrated on" + d + "are: " + no_of_inst);
}
});
}
}
<!DOCTYPE html>
<html>
<head>
<title>Migration Status</title>
<!--<link rel="stylesheet" href="styles.css">-->
<div>
<h3> M I G R A T I O N - S T A T U S </h3>
</div>
<meta charset="utf-8">
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.208.0.min.js"></script>
</head>
<body>
<p>Select Filters to get your ec2 graph :</p>
<form>
<div class = "css-grid1">
<label> Launch-time: </label>
</div>
<div class = "css-inlineblock1">
<label for="fromdate">From Date:</label>
<input type="date" id="fromdate" name="fromdate" min="2017-01-01">
<label for="todate">To Date:</label>
<input type="date" id="todate" name="todate">
</div>
<div class = "css-button">
<input type="submit" id="sbmt" onclick="applyFilters()">
</div>
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>
<div id="demo4"></div>
<div id="demo5"></div>
<div id="demo6"></div>
<div id="demo7"></div>
<div id="demo8"></div>
</form>
<script>
</script>
</body>
</html>

Event listener code won't execute function as expected

I am trying to write a small javascript function which takes data from OpenSignal and then displays it in an html table.
This worked fine up until the point where I tried to make it user friendly by adding in an html form to accept the postcodes input. I tried to avoid using PHP to do this as my client won't have this installed.
I am adding an event listener to the submit button to detect when the form data has been submitted. I am then taking this and validating the string contains valid postcode(s). If they're invalid the program spits out an alert which says "Sorry but you seem to have entered an incorrect postcode.".
If not then I am taking the postcodes and passing them into my function processPostcodesOnServer(). The thing is that this doesn't work inside the event listener. When I pass postcodes in manually using javascript arrays and call the function outside of the event listener everything works fine. When I put it in the event listener it simply doesn't work. I have checked all the inputs to the function are correct and have stepped through the whole program numerous times and cannot find out what is causing the problem. It seems to me this is just another case of Javascripts random behaviour.
Can anyone help?? This is my HTML and Javascript files (I am using some JQuery so you will have to link with the latest version if you want to run this).
<!DOCTYPE html>
<html>
<head>
<title>Mobile Signals</title>
<script src="jquery-1.11.3.min.js"></script>
<script src="NetworkStats.js"></script>
</head>
<body>
<form id="postcodeForm">
Enter postcodes separated by commas<br>
<input type="text" id="postcodes" name="postcodes">
</br></br>
<input type="submit" value="Submit" id="submitButton">
</form>
<div id="theDiv">
</div>
<div id ="secondDiv"> </div>
<table id="theTable" border="1">
</table>
And Javascript
$( document ).ready(function() {
document.getElementById('submitButton').addEventListener('click', function() {
var input = $('#postcodeForm').serializeArray();
var postcodeString = input[0]["value"];
var output = postcodeString.split(",");
var postcodeString = "";
// check each postcode to see if there is any false postcodes
for (var postcode in output) {
var newPostcode = checkPostCode(output[postcode]);
if (newPostcode) {
postcodeString += " true ";
} else {
postcodeString += " false ";
}
}
if (postcodeString.indexOf("false") >= 0) {
// string contains a false so output an error message
window.alert("Sorry but you seem to have entered an incorrect postcode.")
} else {
// all the postcodes are correct, proceed to perform operations on them
processPostcodesOnServer(output);
}
}, false);
function processPostcodesOnServer(output) {
var apiKey = "c590c63f5b3818271a87a3e89fa215ae";
var distance = 10;
var tableNumber = 0;
//var output = ["WR141NE"];
for (var postcode in output) {
strippedPostcode = output[postcode].replace(/ /g,'');
getLatAndLong(strippedPostcode);
}
function googleCallback(latitude, longitude, postcode) {
contactServer(latitude, longitude, postcode);
}
/* Function to contact google and convert the postcode to lat long */
function getLatAndLong(postcode) {
var latitude;
var longitude;
var googleXmlHttp = new XMLHttpRequest();
var googleUrl = "http://maps.googleapis.com/maps/api/geocode/json?address="+ postcode + "&sensor=false";
googleXmlHttp.onreadystatechange = function() {
if (googleXmlHttp.readyState == 4 && googleXmlHttp.status == 200) {
var latLong = JSON.parse(googleXmlHttp.responseText);
latitude = latLong.results[0].geometry.location.lat;
longitude = latLong.results[0].geometry.location.lng;
googleCallback(latitude, longitude, postcode);
}
}
googleXmlHttp.open("GET", googleUrl, true);
googleXmlHttp.send();
}
function contactServer(latitude, longitude, postcode) {
var xmlhttp = new XMLHttpRequest();
var networkStatsUrl = "http://api.opensignal.com/v2/networkstats.json?lat="+latitude+"&lng="+longitude+"&distance=" + distance + "&apikey=" + apiKey;
/*
Functions to contact server and read JSON response back for NetworkStats
*/
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
sortTableData(myArr, postcode);
//displayData(myArr);
}
}
xmlhttp.open("GET", networkStatsUrl, true);
xmlhttp.send();
var functionCount = -1;
function sortTableData(arr, postcode) {
tableNumber++;
$("body").append("</br>" + postcode + "</br>");
theTable = "<table id='table"+ tableNumber + "' border='1'> </table>"
$("body").append(theTable);
var column1 = new Array();
var column2 = new Array();
var column3 = new Array();
var column4 = new Array();
var column5 = new Array();
var column6 = new Array();
var column7 = new Array();
//var output = '<table border="1">';
//var output = "";
for (var obj in arr) {
// find all the networks
if ((typeof arr[obj] === 'object') && (obj == "networkRank")) {
var networks = new Object();
networks = arr[obj];
var allNetworkKeys = Object.keys(networks);
//console.log(allNetworkKeys);
var networksArray = new Array();
$.each(networks, function(networkKey, networkValue){
//Do something with your key and value.
column1.push(networkKey);
if (networkKey.substring(0, 7) == "network") {
$.each(networkValue, function(networkTypeKey, networkTypeValue){
if (networkTypeKey == "type2G") {
column2.push('');
column3.push(networkTypeKey);
for (var variable in networkTypeValue) {
column2.push(variable);
column3.push(networkTypeValue[variable]);
}
} else if (networkTypeKey == "type3G") {
column4.push('');
column5.push(networkTypeKey);
for (var variable in networkTypeValue) {
column4.push(variable);
column5.push(networkTypeValue[variable]);
}
} else if (networkTypeKey == "type4G") {
column6.push('');
column7.push(networkTypeKey);
for (var variable in networkTypeValue) {
column6.push(variable);
column7.push(networkTypeValue[variable]);
}
}
});
//console.log(column1);
}
//console.log(column1, column2, column3, column4);
displayTable(column1, column2, column3, column4, column5, column6, column7);
column1 = []; column2 = []; column3 = []; column4 = []; column5 = []; column6 = []; column7 = [];
});
}
}
}
var counter = 0;
function displayTable(column1, column2, column3, column4, column5, column6, column7) {
var output = ""
//console.log(counter);
counter++;
var column1Length = column1.length;
var column2Length = column2.length;
var column3Length = column3.length;
var column4Length = column4.length;
var column5Length = column5.length;
var column6Length = column6.length;
var column7Length = column7.length;
var highestNumber = Math.max(column1Length, column2Length, column3Length, column4Length, column5Length, column6Length, column7Length);
for (var i=0; i<highestNumber; i++) {
var column1Reference = column1[i];
var column2Reference = column2[i];
var column3Reference = column3[i];
var column4Reference = column4[i];
var column5Reference = column5[i];
var column6Reference = column6[i];
var column7Reference = column7[i];
if (column1Reference === void 0) {
column1Reference = " "
}
if (column2Reference === void 0) {
column2Reference = " "
}
if (column3Reference === void 0) {
column3Reference = " "
}
if (column4Reference === void 0) {
column4Reference = " "
}
if (column5Reference === void 0) {
column5Reference = " "
}
if (column6Reference === void 0) {
column6Reference = " "
}
if (column7Reference === void 0) {
column7Reference = " "
}
output += "<tr>";
output += "<td>" + column1Reference + "</td>";
output += "<td>" + column2Reference + "</td>";
output += "<td>" + column3Reference + "</td>";
output += "<td>" + column4Reference + "</td>";
output += "<td>" + column5Reference + "</td>";
output += "<td>" + column6Reference + "</td>";
output += "<td>" + column7Reference + "</td>";
output += "</tr>";
}
//output += "</table>";
//var table = document.getElementById('theTable');
//console.log(output);
//oldOutput = table.innerHTML;
//table.innerHTML = oldOutput + output;
$("#table" +tableNumber).append(output);
console.log(output);
}
}
}
});
Alright, I got it working.
The table would actually be displayed, if only submitting the form wouldn't reload the page.
There are two ways around this:
Change your click handler to a submit handler and cancel the event!
Replace
document.getElementById('submitButton').addEventListener('click', function() {
// ...
}, false);
by
document.getElementById('postcodeForm').addEventListener('submit', function(event) {
event.preventDefault();
// ...
}, false);
Remove the form:
That would be as simple as removing <form id="postcodeForm"> and </form> from your HTML code, but since you use $('#postcodeForm') in JS, you're gonna have to change
var input = $('#postcodeForm').serializeArray();
var postcodeString = input[0]["value"];
var output = postcodeString.split(",");
into
var output = document.getElementById('postcodes').value.split(",");
to make it work.
(Inlining postcodeString is not actually necessary, but I suggest it, see below.)
If you go with this option, I suggest also removing the name attribute from #postcodes, simply because it serves no purpose.
But regardless of which option you choose, you should fix all those </br>s: It's <br> in HTML 5 (and it was <br/> in HTML 4, but never </br>).
(And don't forget those in your JS!)
And what is the googleCallback function good for, if it only passes its arguments to a function with the exact same list of parameters? Why not use contactServer directly?
And this code is really inefficient:
var postcodeString = "";
// check each postcode to see if there is any false postcodes
for(var postcode in output)
{
var newPostcode = checkPostCode(output[postcode]);
if(newPostcode)
{
postcodeString += " true ";
}
else
{
postcodeString += " false ";
}
}
if(postcodeString.indexOf("false") >= 0)
{
// string contains a false so output an error message
window.alert("Sorry but you seem to have entered an incorrect postcode.")
}
else
{
// all the postcodes are correct, proceed to perform operations on them
processPostcodesOnServer(output);
}
I mean, strings, really? Consider:
// check each postcode to see if there is any invalid postcodes
for(var postcode in output)
{
if(checkPostCode(output[postcode]) === false)
{
// current postcode is invalid so output an error message and return
window.alert("Sorry but you seem to have entered an incorrect postcode.");
return;
}
// at this point, all the postcodes are valid, proceed to perform operations on them
processPostcodesOnServer(output);
Also, you use a lot of variables only exactly once, resulting in quite an overhead.
For example, this:
var column1Length = column1.length;
var column2Length = column2.length;
var column3Length = column3.length;
var column4Length = column4.length;
var column5Length = column5.length;
var column6Length = column6.length;
var column7Length = column7.length;
var highestNumber = Math.max(column1Length, column2Length, column3Length, column4Length, column5Length, column6Length, column7Length);
Which could be shortened to this:
var highestNumber = Math.max(column1.length, column2.length, column3.length, column4.length, column5.length, column6.length, column7.length);
Sure this makes the line a little longer, but for 7 additional characters you can save 7 entire lines!
Or, your displayTable function could really be shortened to this:
function displayTable()
{
var output = '';
var highestNumber = Math.max(arguments[0].length, arguments[1].length, arguments[2].length, arguments[3].length, arguments[4].length, arguments[5].length, arguments[6].length);
for(var i = 0; i < highestNumber; i++)
{
output += '<tr>';
for(var j = 0; j < 7; j++)
{
output += '<td>' + arguments[j][i] + '</td>';
}
output += '</tr>';
}
$('#table' + tableNumber).append(output);
}
Then, you have a lot of {1} in your RegEx - why? [0-9]{1} is equal to [0-9] (or \d, but with that be careful to escape \ if using it in strings).
And finally, I suggest you run your code through JSHint or something similar to get rid of inconsistencies (be careful with JSLint though, that one has really aggressive and unreasonable conventions).
You have var postcodeString twice.
var keyword should only be used once per scope.

Parsing to a table in Javascript

I'm trying to create a calander that can later be styled with CSS. Here is the JS and HTML codes. There is a CSS stylesheet as well but its just used for color and positioning. In the Javascript, I would like to build the table based off the first and last days of the month and insert a new row at the end of each week. As is the Javascript does nothing. When you remove the first if statement, it seems to iterate only once. I'm not sure where I'm screwing up in trying to create the table.
function setDate() {
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
var day = today.getDate();
document.getElementById("myDay").value = day;
document.getElementById("myMonth").value = month;
document.getElementById("myYear").value = year;
}
function buildCalendar() {
var firstDate = new Date(document.getElementById("myYear").value, document.getElementById("myMonth").value, 1);
var weekDay = firstDate.getDay();
var theDate = firstDate.getDate();
var theMonth = firstDate.getMonth();
var theYear = firstDate.getFullYear();
var newDay = new Date(theYear, theMonth + 1, 1);
var lastDate = new Date(newDay - 1);
var lastDay = lastDate.getDate();
document.write("<table class='caltable' border='1'><tr><th>");
document.write("<tr><th>Sunday</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th>");
document.write("</th></tr>");
var col = 0;
for (var i = theDate; i < lastDay + 1; i++) {
if (col == 0) {
document.write("<tr><td>" + i "</td>");
}
if (col == 6) {
document.write("<td>" + i + "</td></tr>");
col == 0;
} else {
document.write("<td>" + i + "</td>");
col++;
}
}
document.write("</table>");
}
function getMonthName() {
var e = getElementById("myMonth").selectedIndex;
var monthName = e.options[e.selectedIndex].text;
return monthName;
}
Here is the HTML file. It's basically just a wrapper div with some other divs inside for holding the calendar eventually a scheduler, as well as the current date. Right now I'm simply trying to get the the table (see the javascript) to build. Ideally it would be in the div with the id "bottomLeft".
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel = "stylesheet" type = "text/css" href = "./CSS/calendar.css">
<script type = "text/javascript" src = "./Calendar/calendar.js"></script>
<script type = "text/javascript" src = "./Calendar/task.js"></script>
</head>
<body onLoad = "setDate(); buildCalendar();">
<div id = "wrapper">
<div id = "left"> Left Div </div>
<div id = "right"> Right Div </div>
<div id = "bottomLeft"> Shows calendar </div>
<div id = "topLeft"> Day:<input id = "myDay" type="number" min = "1" max = "31">Month:<select id = "myMonth"><option value = "0">January</option> <option value = "1">February</option><option value = "2">March</option><option value = "3">April</option><option value = "4">May</option><option value = "5">June</option><option value = "6">July<option value = "7">August</option><option value = "8">September</option><option value = "9">October</option><option value = "10">November</option><option value = "11">December</option></select> Year:<input id = "myYear" type = "number" min = "100"> TopLeft Div shows form components for date </div>
<div id = "topRight"> Shows the form to add task </div>
<div id = "bottomRight"> Show list of tasks </div>
</div>
</body>
</html>
In addition to the mistakes Ceesie123456 mentioned, you need to remove the extra <tr><th> from the opening table tag string. As a means of getting the calendar into the bottomLeft div, you can use set the element's innerHTML property. Finally, you're missing a piece of logic which check for when the end of the calendar is not the end of a row, which means the table won't line up correctly. So, an example:
function buildCalendar(){
var firstDate = new Date(document.getElementById("myYear").value, document.getElementById("myMonth").value, 1);
var weekDay = firstDate.getDay();
var theDate = firstDate.getDate();
var theMonth = firstDate.getMonth();
var theYear = firstDate.getFullYear();
var newDay = new Date(theYear, theMonth + 1, 1);
var lastDate = new Date(newDay - 1);
var lastDay = lastDate.getDate();
var tableString = ("<table class='caltable' border='1'>");
tableString = tableString + ("<thead><tr><tr><th>Sunday</th><th>Monday</th><th>Tuesday</th><th>Wednesday</th><th>Thursday</th><th>Friday</th><th>Saturday</th></tr></thead>");
tableString = tableString + "<tbody>";
var col = 0;
for (var i = theDate; i <= lastDay; i++)
{
if(col == 0)
{
tableString = tableString + ("<tr>");
}
tableString = tableString + "<td>" + i + "</td>";
if (col == 6 || i == lastDay)
{
tableString = tableString + ("</tr>");
col = 0;
}
else
{
col++;
}
}
tableString = tableString + ("</tbody></table>");
document.getElementById("bottomLeft").innerHTML = tableString;
}
U made a few mistakes in ur Javascript code.
if (col == 6)
{
document.write("<td>" + i + "</td></tr>");
col == 0; //this should be changed to col = 0; with col = 0; u set col to 0.
}
and
if(col == 0)
{
document.write("<tr><td>" + i "</td>");
}
u should change it to:
if(col == 0)
{
document.write("<tr><td>" + i + "</td>"); // combine string with variable and string.
}

Need help debugging a Javascript code and/or getting it to work

Been pulling my hair out since the past 4 hours. I have two Javascript file, both works completely fine by itself. One is use as a login verification, the other takes my registration page and writes the form to an XML file.
When I took some code from my login JS and place it in my registration JS, my registration JS doesn't even function properly. I'm thinking my issue is probably the placement of my codes.
If I post the complete codes here, the post would be like 10ft long, so here's all my files:
http://www.mediafire.com/?wt9bchq35pdqxgf
By the way, this is not a real world application, it's just something I'm doing.
Here's my original Javascript file for the registration page:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'C:\\Users\\Wilson Wong\\Desktop\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++)
{
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '" ');
file.WriteLine('></Person>\n');
} // end for countr
//file.WriteLine('></Person>\n');
var usrn = document.getElementById("Usrn").value;
var pswd = document.getElementById("Pswd").value;
var pid = document.getElementById("PersonID").value;
var fname = document.getElementById("FirstName").value;
var lname = document.getElementById("LastName").value;
var gender = document.getElementById("Gender").value;
var dob = document.getElementById("DOB").value;
var title = document.getElementById("Title").value;
file.Write(' <Person ');
file.Write('Usrname="' + usrn + '" ');
file.Write('Pswd="' + pswd + '" ');
file.Write('PersonID="' + pid + '" ');
file.Write('FirstName="' + fname + '" ');
file.Write('LastName="' + lname + '" ');
file.Write('Gender="' + gender + '" ');
file.Write('DOB="' + dob + '" ');
file.Write('Title="' + title + '" ');
file.WriteLine('></Person>\n');
file.WriteLine('</PersonInfo>\n');
file.Close();
} // end SaveXML function --------------------
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
This code here will write to my XML file after I hit the submit button. And this is how the XML looks like:
<?xml version="1.0" encoding="utf-8"?>
<PersonInfo>
<Person Usrname="Bob111" Pswd="Smith111" PersonID="111" FirstName="Bob" LastName="Smith" Gender="M" DOB="01/01/1960" Title="Hello1" ></Person>
<Person Usrname="Joe222" Pswd="Johnson222" PersonID="222" FirstName="Joe" LastName="Johnson" Gender="M" DOB="12/01/1980" Title="Hello2" ></Person>
<Person Usrname="Tracey333" Pswd="Wilson333" PersonID="333" FirstName="Tracey" LastName="Wilson" Gender="F" DOB="12/01/1985" Title="Hello3" ></Person>
<Person Usrname="Connie444" Pswd="Yuiy444" PersonID="444" FirstName="Connie" LastName="Yuiy" Gender="F" DOB="12/01/1985" Title="Hello4" ></Person>
<Person Usrname="Brian555" Pswd="Dame555" PersonID="555" FirstName="Brian" LastName="Dame" Gender="M" DOB="12/01/1985" Title="Hello5" ></Person>
<Person Usrname="Scott666" Pswd="Bikes666" PersonID="666" FirstName="Scott" LastName="Bikes" Gender="MF" DOB="12/01/1985" Title="Hello6" ></Person>
<Person Usrname="sadsa" Pswd="s" PersonID="s" FirstName="s" LastName="s" Gender="s" DOB="s" Title="s" ></Person>
If I modify my code to what is shown below, the XML file won't even create. Nor will the authentication run properly. As in the the box won't turn red and no alert message pops up. But the codes I add in does work on my other JS file for my log in page.
Here's the edited registration JS:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'C:\\Users\\Wilson Wong\\Desktop\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++)
{
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '" ');
file.WriteLine('></Person>\n');
} // end for countr
var usrn = document.getElementById("Usrn").value;
var pswd = document.getElementById("Pswd").value;
var pid = document.getElementById("PersonID").value;
var fname = document.getElementById("FirstName").value;
var lname = document.getElementById("LastName").value;
var gender = document.getElementById("Gender").value;
var dob = document.getElementById("DOB").value;
var title = document.getElementById("Title").value;
var errmsg = "empty field";
var errmsg2 = "You have register successfully";
var msg = "This user name is already in use"; //this is what I added
var errCount = 0;
errCount += LogInVal(usrn);
errCount += LogInVal(pswd);
errCount += LogInVal(pid);
errCount += LogInVal(fname);
errCount += LogInVal(lname); //this is what I added
errCount += LogInVal(gender);
errCount += LogInVal(dob);
errCount += LogInVal(title);
if (errCount != 0) //the if/else statements are what I added
{
file.WriteLine('</PersonInfo>\n'); //checks to see if textbox is empty, if yes, alert
file.Close();
alert(errmsg);
return false;
}
else if(authentication(usrn) == true)
{
file.WriteLine('</PersonInfo>\n'); //checks to see if user name entered is already in use
file.Close();
alert(msg);
return false;
}
else
{
file.Write(' <Person ');
file.Write('Usrname="' + usrn + '" ');
file.Write('Pswd="' + pswd + '" ');
file.Write('PersonID="' + pid + '" ');
file.Write('FirstName="' + fname + '" ');
file.Write('LastName="' + lname + '" '); //this block of code here was there originally
file.Write('Gender="' + gender + '" ');
file.Write('DOB="' + dob + '" '); //previous two condition is false, registration successful, writes to XML.
file.Write('Title="' + title + '" ');
file.WriteLine('></Person>\n');
file.WriteLine('</PersonInfo>\n');
file.Close();
alert(errmsg2);
return true;
}
} // end SaveXML function --------------------
function authentication(usrname1) //function was added
{
for (var x = 0; x < arrPerson.length; x++)
{
if (arrPerson[x][0] == usrn)
{
return true;
}
}
return false;
}
function LogInVal(objtxt) //function was added
{
if(objtxt.value.length == 0)
{
objtxt.style.background = "red";
return 1;
}
else
{
objtxt.style.background = "white";
return 0;
}
}
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
Here's the login page JS, which contains the code(it works fine in this file) that was added to the registration JS:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
//DEFINE LOAD METHOD
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
xmlObj = xmlDoc.documentElement;
}
//declare & initialize array
var arrPerson = new Array();
//initialize array w/ xml
function initialize_array()
{
LoadXML("PersonXML.xml");
var x = 0;
while (x < xmlObj.childNodes.length)
{
var tmpArr = new Array(xmlObj.childNodes(x).getAttribute("Usrname"),
xmlObj.childNodes(x).getAttribute("Pswd"),
xmlObj.childNodes(x).getAttribute("FirstName"),
xmlObj.childNodes(x).getAttribute("LastName"),
xmlObj.childNodes(x).getAttribute("DOB"),
xmlObj.childNodes(x).getAttribute("Gender"),
xmlObj.childNodes(x).getAttribute("Title"));
arrPerson.push(tmpArr);
x++;
}
}
//Validation
function LogInVal(objtxt)
{
if(objtxt.value.length == 0)
{
objtxt.style.background = "red";
return 1;
}
else
{
objtxt.style.background = "white";
return 0;
}
}
//main validation
function MainVal(objForm)
{
var errmsg = "empty field";
var errmsg2 = "Incorrect Username and Password";
var msg = "You have logged in successfully";
var errCount = 0;
var usrn = document.getElementById("usrname1").value;
var pswd = document.getElementById("pswd1").value;
errCount += LogInVal(objForm.usrname);
errCount/*1*/ += LogInVal(objForm.pswd);
initialize_array();
if (errCount != 0)
{
alert(errmsg);
return false;
}
else if(authentication(usrn, pswd) == true)
{
alert(msg);
return true;
setCookie('invalidUsr',' ttttt');
}
else
{
alert(errmsg2);
return false;
}
}
function authentication(usrname1, pswd1)
{
for (var x = 0; x < arrPerson.length; x++)
{
if (arrPerson[x][0] == usrname1 && pswd1 == arrPerson[x][1])
{
return true;
}
}
return false;
}
function setCookie(Cookiename,CookieValue)
{
alert('executing setCookie');
document.cookie = Cookiename + '=' + CookieValue;
}
Here's my registration HTML page:
<html>
<!--onSubmit="SaveXML(person);"-->
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
</head>
<body>
<script type="text/javaScript" src="writeXML.js"> </script>
<div class="form">
<form id="Registration" name="reg" action="" method="get" onSubmit="return initialize_array()">
Username:<input type="text" name="Usrn" id="Usrn" maxlength="10"/> <br/>
Password:<input type="password" name="Pswd" id="Pswd" maxlength="20"/> <br/>
<hr>
PersonID:<input type="text" name="PersonID" id="PersonID"/> <br>
<hr>
First Name:<input type="text" name="FirstName" id="FirstName"/> <br>
Last Name:<input type="text" name="LastName" id="LastName"/>
<hr>
DOB:<input type="text" name="DOB" id="DOB"/> <br>
<hr>
Gender:<input type="text" name="Gender" id="Gender"/> <br>
<hr>
Title:<input type="text" name="Title" id="Title"/> <br>
<hr>
<!--Secret Question:<br>
<select name="secret?">
</select> <br>
Answer:<input type="text" name="answer" /> <br> <br>-->
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Hope I'm not being too confusing.
What I see in the code is this:
create XML file, start with <personInfo>
if error, skip </personInfo>
now add something else.
so you're not closing the XML element. Of course it won't create the file. It won't write invalid XML, and that's "expected" behavior.
You can also debug your jvascript code to enable javascript debugging. go to : tools > intenet options > advanced > browsing and uncheck (disable script debugging). in Internet Explorer Browser . then you can attach debugger by writing debugger; # any location in javascript function egs:
function SaveXML(UserData)
{
debugger;
var file = fso.CreateTextFile(FILENAME, true); file.WriteLine('\n');
file.WriteLine('\n');
.........................
}

Categories

Resources