parseInt() returns NaN instead of integer - javascript

I'm trying to implement a route-finder using javascript. To do so, I create a grid from a 2d array, and insert 'x' (walls), 'o' (open space), '0' (start), and 'g' (goal). I would like to increment the open squares from the start to the goal, so I end up with something that looks like this: '0',1,2,3,4,5 ... g
However, my grid never goes past 0 and 1. My console keeps returning NaN for the remaining open spaces and I suspect it's a typeError from using parseInt(). Please see my code below - I really appreciate your help.
<!DOCTYPE html>
<head>
<link rel='stylesheet' type='text/css' href = 'routes.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body></body>
<script>
//o is an open space x is a wall
var a = [['0','o','x','x'],
['x','o','o','o'],
['x','o','x','o'],
['x','o','o','g']];
/*printed grid looks like this
var a = [[0,1,'x','x'],
['x',NaN,NaN,NaN],
['x',NaN,'x',NaN],
['x',NaN,NaN,'g']];*/
function move(startR,startC){ //(0,0) startR,startC
var north = startR-1;
var south = startR+1;
var east = startC+1;
var west = startC-1;
//discard all the out of bounds locations
if (north<0){north=startR;}
if (south>3){south=startR;}
if (east>3){east=startC;}
if (west<0){west=startC;}
if (a[north][startC]=='o'){newLocation(north,startC,startR,startC);}
if (a[south][startC]=='o'){newLocation(south,startC,startR,startC);}
if (a[startR][west]=='o'){newLocation(startR,west,startR,startC);}
if (a[startR][east]=='o'){newLocation(startR,east,startR,startC);}
}
//newLocation() increments square I just moved to and pass the new location to the function 'move '
function newLocation(northSouth,eastWest,origR,origC){
var origValue = parseInt(a[origR,origC]);
console.log(origValue); //prints NaN to console
var newValue = ++origValue;
a[northSouth][eastWest]=newValue;
console.log(a[origR,origC]);
return move(northSouth,eastWest);
}
move(0,0);
//print board to screen
for (r=0;r<4;r++){
document.write('<br>');
for (c=0;c<4;c++){
var l = document.createElement('div');
var t = document.createTextNode(a[r][c]);
$(l).addClass('letterboxes');
l.appendChild(t);
document.body.appendChild(l);
// document.body.appendChild(letter);
}
}
</script>
</html>

Related

How to setup a while loop with variables

I'm wanting to setup a while loop in heading 1 that allows a user to input three employees names with hours worked, hourly wage, and total pay. The loop needs to calculate those, account for overtime (over 40 hours receives 1.5x pay for any hours over 40), and display all three employees information after calculating.
What do I need to fix with my code to achieve the desired result?
I've referred to W3Schools and Youtube on "Creating a while loop" and "Declaring variables".
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta charset="ISO-8859-1">
<title>JavaScript Page</title>
<script language="javascript">
"<h1> Martha's Diner</h1>"
// Variables get declared
var employeeCount; employeeCount = "3";
var hoursWorked; hoursWorked = " ";
var hourlyWage; hourlyWage = " ";
var notOvertime; notOvertime = "<=40";
var overTime; Overtime = ">40";
var totalPay; totalPay = "overTime + notOvertime";
var employeeName = " ";
var i = 0;
/// While Loop
while (i < employeeCount) {
employeeName = window.prompt ("Enter an Employee Name");
hoursWorked = window.prompt ("Enter Hours Worked");
hourlyWage = window.prompt ("Enter Hourly Wage");
if (hoursWorked <= 40)
hourlyWage * hoursWorked;
i++
}
</script>
</head>
<body>
</body>
</html>
I expected the loop to end and calculate keyed information, but the loop doesn't stop or calculate at all.
you are running an infinite while loop as any positive integer in java or javascript takes as true and check your closing loop braces.To input three values using while you can try like this:
var a=0;
while(a<3)
{
//your codes
//your codes
a=a+1;
}
this will execute 3 times

doesnt get in the if statement javascript DOM

so I have to get the bigger salary of the average salary and to print the name of the person, but I don't get in the if at least the alert says so. Here is my code:
<html>
<body>
<script type="text/javascript">
xDOC = new ActiveXObject("Microsoft.XMLDOM");
xDOC.async = "false";
xDOC.load("pti_project.xml");
x = xDOC.getElementsByTagName("person");
alert(x.length);
var avgsal = 11450 / x.length;
for (var i = 0; i < x.length; i++) {
var salary = x[i].getElementsByTagName("salary");
if (salary * 1 > avgsal * 1) {
alert("1");
var person = x[i].getElementsByTagName("name");
document.write(person[0].childNodes[0].nodeValue);
}
}
document.write(avgsal);
</script>
</body>
</html>
No clue why is this happens, it should work.
How its name says, the method getElementsByTagName() returns a collection of objects, not their values.
Look at the example in this page: https://msdn.microsoft.com/en-us/library/ms765549(v=vs.85).aspx
The result of the function is iterated with a for loop to get each matched element and then its xml property is printed.
Something like:
(salary.length > 0 ? parseFloat(salary.item(0).xml) : 0)
would work for you instead of only salary.
This expression will check if the collection is not empty and if so will get the content of first element. Otherwise will return zero.
Here is my answer to my question I needed little time , but I made it . So here is the code if somebody needs help with such type of situation :
<html>
<body>
<script type="text/javascript">
xDOC=new ActiveXObject("Microsoft.XMLDOM");
xDOC.async="false";
xDOC.load("pti_project.xml");
x=xDOC.getElementsByTagName("person");
var avgsal = 11450/x.length;
for(var i=0; i<x.length; i++)
{
var salary=x[i].getElementsByTagName("salary");
if(salary[0].childNodes[0].nodeValue>avgsal*1)
{
var person=x[i].getElementsByTagName("name");
document.write(person[0].childNodes[0].nodeValue);
document.write("<br>");
}
}
</script>
</body>
</html>

How to use an element property to pass a variable from Javascript

I'm attempting to send emails using an HTML template.
I've looked at this post:
(https://stackoverflow.com/questions/33178702/passing-variables-into-html-code)
Would either of the two code examples be close to something that could work to pass the variables from the Javascript to the HTML template?
My javascript variables are named detail2, detail3, detail4, detail5 and detail6.
1st attempt:
<html>
<head>
<script>
{
var detail2 = document.getElementById("detail2").innerHTML;
var detail3 = document.getElementById("detail3").innerHTML;
var detail4 = document.getElementById("detail4").innerHTML;
var detail5 = document.getElementById("detail5").innerHTML;
var detail6 = document.getElementById("detail6").innerHTML;
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
2nd attempt:
<html>
<head>
<script>
{
<input type="hidden" id="Detail2" value="detail2" />
<input type="hidden" id="Detail3" value="detail3" />
<input type="hidden" id="Detail4" value="detail4" />
<input type="hidden" id="Detail5" value="detail5" />
<input type="hidden" id="Detail6" value="detail6" />
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
Finally, the method given on GAS Dev is below, but this only confuses me more. I am sure I've been at this too long and I'm burned out, I just can't seem to see the answer on this one.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</body>
</html>
If anyone can help it's much appreciated!
Below is the Javascript from the .gs script file.
function SendEmail() {
// initialize data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getDataRange();
var values = range.getValues();
// iteration loop
for (var i = 1; i<values.length; i++) {
// current times for comparator
var month = new Date().getMonth(); // returns today as 0-11 -- Jan is 0
var day = new Date().getDate(); // returns today as 1-31
var hour = new Date().getHours(); // returns today as 0-23
var minute = new Date().getMinutes(); // returns today as 0-59
// pull data from spreadsheet rows
var company = values[i][0];
var rating = values[i][1];
var detail1 = values[i][2];
var detail2 = values[i][3];
var detail3 = values[i][4];
var detail4 = values[i][5];
var detail5 = values[i][6];
var sendTime = values[i][7];
// character send times for comparator
var cSendMonth = sendTime.getMonth(); // returns sendMonth as 0-11 -- Jan is 0
var cSendDay = sendTime.getDate(); // returns sendDay as 1-31
var cSendHour = sendTime.getHours(); // returns sendHour as 0-23
var cSendMinute = sendTime.getMinutes(); // returns sendMinute as 0-59
// comparator
if(cSendMonth == month) {
if(cSendDay == day) {
if(cSendHour == hour) {
if(cSendMinute == minute) {
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: 'Test Email markup2 - ' + new Date(),
htmlBody: htmlBody,
});
} // end if minute test
}// end if hour test
}// end if day test
}// end if month test
}// end for loop
}
Can you try:
<html>
<head>
<script>
(function() {
var detail2 = document.getElementById("detail2").innerHTML;
document.getElementById("detail2_val").innerHTML = detail2;
})();
</script>
</head>
<body>
<p>
<br>"Punctual?" <span id="detail2_val"></span><br>
</p>
</body>
</html>
Currently, this line:
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
will not evaluate a template.
The method being used is:
createHtmlOutputFromFile('mail_template')
HtmlService has quite a few methods for creating html content. You need to use:
HtmlService.createTemplateFromFile(filename).evaluate()
There are some possible things that could go wrong in your overall work flow. If the situation is one in which you are writing data, and then immediately trying to read that same data that was just written, there could be a problem with the new data not being available to be read in such a short time span.
I would use:
SpreadsheetApp.flush();
immediately after writing the new data, and before creating the template.
Only your third html example has code for a template. To retrieve data and put it into a template, a scriptlet must either run a function, that then retrieves the data, or the data must be in global variables. The situation with global variable makes no sense, because you are using dynamic data, so a function would need to run to first put the data into a global variable. The function might as well just return the data directly. So, your scriptlet will probably need to run a server side function and return text or HTML to the html template. You probably need to use a printing scriptlet.
Apps Script documentation - force printing scriptlets

Jackhammers not changing on mouseover

I'm trying to get the image to change based on one second timer, but the image stays one the first object in the array
the code I have so far is
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 8 - Jackhammer Man</title>
<script type="text/javascript">
var jackhammers = new Array();
jackhammers[0] = "<img src='Images/jackhammer0.gif'>";
jackhammers[1] = "<img src='Images/jackhammer1.gif'>";
jackhammers[2] = "<img src='Images/jackhammer2.gif'>";
jackhammers[3] = "<img src='Images/jackhammer2.gif'>";
jackhammers[4] = "<img src='Images/jackhammer4.gif'>";
jackhammers[5] = "<img src='Images/jackhammer5.gif'>";
jackhammers[6] = "<img src='Images/jackhammer6.gif'>";
jackhammers[7] = "<img src='Images/jackhammer7.gif'>";
jackhammers[8] = "<img src='Images/jackhammer8.gif'>";
jackhammers[9] = "<img src='Images/jackhammer9.gif'>";
jackhammers[10] = "<img src='Images/jackhammer10.gif'>";
var curJackhammer;
function bounce() {
var img = document.getElementsByTagName("img");
var i = 0 ;
for (i = 0; i<10;i++) {
if(jackhammers[i].src == img.src) {
if(i === jackkhammers.length) {
img.src = jackhammers[0].src;
break;
}
img.src = jackhammers[i+1].src;
break;
}
}
}
</script>
</head>
<body>
<img onMouseOver="setInterval(function(){bounce},1000);" onMouseOut="clearInternval(fuction(){bounce};" src="Images/jackhammer0.gif" id="hammer" name="hammerman" alt="Jackhammer Man">
</body>
</html>
The issue I'm coming across is the mouseover event will not activate, I am having trouble finding the error in my code as the debuggers I have aren't finding any. Any help trying to get the mouseover function of the image changing ever so often would be appreciated.
you have a typo if(i === jackkhammers.length)
jackhammers[x] has no src property so to get its value use it without .src
instead of
onMouseOver="setInterval(function(){bounce},1000);"
write:
onMouseOver="setInterval(function(){bounce();},1000);"
var img = document.getElementsByTagName("img");
This returns a NodeList, or an array of elements. You need to access the index of this element with [0]
Or better yet, use querySelector which returns the first element in a NodeList
You keep referring to the src property of items in the jackhammers array:
img.src = jackhammers[0].src;
even though items in that array are strings, not objects.
Also, there's a typo here:
if(i === jackkhammers.length) {
These kinds of errors would be immediately visible the with dev tools of your browser of choise. Put a breakpoint to where you suspect things go wrong and start investigating variables and your assumptions while stepping through the code.
See here: http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820
Updated code changed a few things around based on some advice from my mentor.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 8 - Jackhammer Man</title>
<script type="text/javascript">
var jackhammers = new Array(11);
jackhammers[0] = "Images/jackhammer0.gif";
jackhammers[1] = "Images/jackhammer1.gif";
jackhammers[2] = "Images/jackhammer2.gif";
jackhammers[3] = "Images/jackhammer3.gif";
jackhammers[4] = "Images/jackhammer4.gif";
jackhammers[5] = "Images/jackhammer5.gif";
jackhammers[6] = "Images/jackhammer6.gif";
jackhammers[7] = "Images/jackhammer7.gif";
jackhammers[8] = "Images/jackhammer8.gif";
jackhammers[9] = "Images/jackhammer9.gif";
jackhammers[10] = "Images/jackhammer10.gif";
var curJackhammer = 0;
var direction;
var begin;
function bounce(){
if(curJackhammer == 10)
curJackhammer = 0;
else
++curJackhammer;
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer].src;
if(curJackhammer == 0)
direction = "up";
else if(curJackhammer == 10)
direction = "down";
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer];
}
function startBouncing(){
if (begin)
clearInterval (begin);
begin = setInterval("bounce()",90);
}
</script>
</head>
<body>
<h1>Jackhammer Man</h1>
<p><img onMouseOver="startBouncing();" onMouseOut="clearInterval(begin);" src="Images/jackhammer0.gif" height="113" width="100" alt="Image of a man with a jackhammer." /></p>
</body>
</html>
>
Used firebug to step into code, works once I set into it but simply putting a mouse over nothing happens.

Javascript Dynamic pointer allocation

I'm wondering whether I can assign the pointer of a variable as something along the lines of
"image"+i+".src"
I've tried using eval, because that's the only suggestion I've found, but I'm being thrown a undefined variable error. Here's my code, if someone wouldn't mind taking a look:
<html>
<head>
<script type="text/javascript">
<!--
m = 0
x = 0
image=[ //Initializes the Array for Image URLs, Add object by adding the full URL in "" with , in between each entry
"http://i.imgur.com/OaElB10.jpg",
"http://i.imgur.com/NTYiEB9.jpg",
"http://i.imgur.com/X1jreGc.jpg"]
function ImgPreloadHandler()
{
l = image.length
for(t=0; t<l; t++)
{
var image+t = new image()
image+t = image[t]
}
}
ImgPreloadHandler()
//-->
</script>
</head>
<body>
<img src="http://i.imgur.com/mv3sV8m.png" name="slide" width="796" height="600" />
<script>
function slideit()
{
var step = 0
var z = step
if (!document.images)//if browser does not support the image object, exit.
return
document.images.slide.src=
if (step<x)
step++
else
step=1
setTimeout("slideit()",2500)//call function "slideit()" every 2.5 seconds
}
slideit()
</script>
</body>
</html>
You can't create a dynamic variable name. But there's plenty of other solutions.
Why not create an Object that contains your image values?
var images = {};
for(t=0; t<l; t++) {
images[image + t] = image[t];
}
console.log(images);
> {
image0: "http://i.imgur.com/OaElB10.jpg",
image1: "http://i.imgur.com/NTYiEB9.jpg",
image2: "http://i.imgur.com/X1jreGc.jpg"
}
By the way, don't use eval :)

Categories

Resources