What do you want to learn? Leverged jhuang@tampa.cgsinc.com Skip to main content Pluralsight uses cookies.Learn more about your privacy Hands-on JavaScript Project: Solar Calculator by Paul Cheney This course targets JavaScript developers who want to practice using functions, variables, loops, switches, operators, etc. Basic understanding of JavaScript is very helpful. Start CourseBookmarkAdd to Channel Table of contents Description Transcript Exercise files Discussion Recommended Course Overview Course Overview Hello, my name is Paul Cheney. Let me tell you about this great hands-on JavaScript course. I believe that the best learning comes when you and I work together to build projects that you might see in the real world. In this Pluralsight course we will be learning about JavaScript functions, loops, switch statements, and gathering information from the Document Object Model, or DOM, using an authentic hands-on approach. Next we'll apply everything we have learned to create a web app that allows customers to calculate how many solar panels they need to power their home. Now I realize you may not need a solar calculator for your next client, but the information you learn here will transfer to other JavaScript projects you work on. As you do so you will remember what you learned so you can apply it in the future. That's the power of hands-on learning, so join me as we work together to learn the fundamentals of JavaScript. Introduction Introduction Hello, this is Paul Cheney, but then you already knew that, so let's get started. You cannot be a web developer unless you know JavaScript, so the purpose of this course is to give you hands-on practice with some of these JavaScript concepts. During the last module of this course you will combine the concepts you've learned to make a fully functional solar calculator. To motivate you to stay with me, let's take a peek at the final project. This is what the final project will look like on a phone. Here's the same project on a tablet. And finally, on a desktop computer screen. The customer will input their monthly kilowatt usage up here, and then use a map to estimate the number of hours of sun they get per day, then they select a solar panel from the drop-down list, and click the Calculate button. At this point, the JavaScript takes over and does its magic. It is my belief that if you can see how JavaScript concepts fit into a real-world application, they'll be easier to learn and remember. So let's take a quick look at the entire course. In module 2 we will explore JavaScript functions while passing values in and out. In module 3 we'll explore loops and several ways to track your JavaScript variables. In module 4 we will explore a switch statement, along with an HTML select element. In module 5 we'll practice extracting information from the Document Object Model, or DOM. Finally, in module 6 we'll combine everything you have learned and build a responsive, mobile-friendly web application to calculate the number of solar panels you need to run your home. Throughout this course, you will not only learn what is happening, but you'll be making it happen on your computer. To be successful in this course you will need some kind of text editor, like Sublime Text, Dreamweaver, Brackets, Visual Studio Code, or even TextWrangler and Notepad ++. You should also know how to connect an external JavaScript file to an HTML document and how to access the JavaScript console in a web browser. It will also be helpful to have several web browsers and mobile devices on hand to test your code. So that's it for the introduction, let's now explore functions. Exploring Functions Overview of Functions Let's take a good hard look at functions. In this module, we will first create a function and then look at several ways to call a function. Next we will pass values into the function and then return values from the function. Finally we will call a function from another function as we build a project that calculates the material needed for a round room. A function is simply a block of code that contains one or more statements that complete a task. The statements inside a function are not triggered until the function is called. To call this function, I use test with a left and right parentheses. The result would be a pop-up on my browser screen. You can also pass values to a function. In this case when we call the test function we will include the name of Jane. Jane gets put into a basket and carried to the function where it is transferred to a new basket called userName. When we perform the alert, we pull the name Jane out of the userName basket and show it on the screen. You can also return values from a function back to a variable. In this case we're going to create a function that calculates the mother's age as 20 years more than her son. Down here we create a variable called motherAge and assign it to the name of the function. We put the son's age between the parentheses. When we call the test function we put a 12 into the basket, the 12 is then put into a variable called sonAge, we use a local variable x and add 20, then return the value of x, which is put into the mother's age variable. Once the program advances to the next line of code, an alert is called and we get a pop-up showing the mother's age as 32. Alright, it's time to get out of theory and start coding. Setup Now we're ready to jump into the actual coding. I've got Sublime Text I'll be using for this particular project, and I have a copy of the startJS.zip file, which I will expand and open. It's got a CSS that is completely empty, it has a JavaScript file that is completely empty, and then an index file that's almost completely empty. So let's take that folder and let's rename it. We'll call it practice1. We'll drag it to our Sublime Text sidebar, and now we can open it and see there's the index file, we'll change this, then we're ready to go. Basic Function Now that we have our project all set up, opened in a browser, and open in our text editor, let's go ahead and put in an alert. Inside the alert we'll put a very simple message. When we refresh the page that alert automatically pops up because it's inline and the JavaScript is executed from top to bottom. If we now wrap this inside of a function, and we'll just call the function test, put the closing function bracket down here, tab that in to make it look nice, save it, now when I refresh it the alert is not triggered because it's hidden inside of a function and there's nothing calling the function. So let's look at two different ways to trigger the content of this function. First of all, we can just go down later in our JavaScript, put test, save it, now when we run it, line 6 calls line 2, line 2 then triggers line 3, and that gives us this pop-up. Let's comment that out. Another way to do is from the HTML, and we're going to create a very simple button, Test the Function. Right now it does nothing except sit there and look pretty. So inside the opening tag we will put onclick=, and the name of the function, test, save it. Now when we refresh it, test, it now calls that function, and there's our message. So there's two different ways to call a function, one from an HTML button and one from a line of code inside of our JavaScript itself. So on line 3 we've used an alert to get a message out of a function and to the user so that I can see it. Another way to do that is actually to do a console.log. In here we can put a similar message, save it, now we're currently triggering this from a button in our HTML. If we hit Refresh and then test the function, nothing appears to have happened. In order to see the results of a console.log, we're going to Inspect, I'm using Chrome, and click on the Console, and now we can see our message popping up in the Console. Using console.log is a great way to track your variables so that you can see what's happening in your program as you're moving from line to line. Function with One Parameter Now let's move onto some more advanced function techniques. I'll go back to my startJS file, which you can download from Pluralsight. Let's rename this one practice2, and we will open practice2 inside of our text editor. We're still going to be using Sublime Text, drag it over, open it up. Inside our JS we are ready to go to work. Let's build a new function and we'll call it floor. What does it take to calculate how much carpet you would need for a round room? Well first of all you have to have the radius, you take the radius and you multiply it by itself, and then you multiply it by Pi, which is math function built into JavaScript, which is very convenient for us. So, we've got a variable, and we're going to call it radius, it's going to equal 4. And then we'll create a new variable called floorArea, and what that's going to equal is Math.PI. Pi is that 3.14 number that you learned about in junior high. We're then going to multiply it by the radius squared. Now there is a math function for doing radius squared, but we're just going to keep it really simple and do radius * radius, it's just much easier. Now that we have that let's do a console.log and we'll take the floorArea and we'll see what it is. Let's go ahead and call it. Let's go back to our Index, change this to Practice 2, double click practice2, there it is, hit Refresh. Once again we've got to pull up the console, and switch, and there it is, 50.2654 is the area of a radius of 4, which means it's 4 from the center to the side. Well, who on Earth can walk into a perfectly round room, know exactly where the center is, and measure from the center to the side, that's not easy. It's much easier to get a diameter. Well a diameter is the area from side to side. So let's do var diameter = 8. And the radius then would equal the diameter/2, let's try that out. You still get the same number. Let's try changing this to 10, and sure enough, our number updates to 78. Well this is useful if all of our rooms in the whole wide world had a diameter of 10, but they don't. So now we need to pass a value in to this function so that it can process and give us the correct floor area for any sized room. So this is the neat thing about it. We'll just come down here into floor and we're going to feed it a number. In this case we'll put the 8. That 8 is going to be put in a little basket, it'll be sent up here, and we will call it diameter. So it moves from the basket, gets put in diameter, we no longer need this because diameter is already assigned a value from this 8, and now let's save it, hit Refresh, and we're back to 50 for a floor of 8. So we just change this to 10, back to 78. So we can put any number in here and it automatically returns the area of that floor. Function with Two Parameters Now that we have our floor function performing well, let's add another function to calculate the area for the walls, which is similar, but slightly more complex. Function walls. In order to calculate the area of a round-room wall we need to have the circumference, which is the distance around, and we need to have the height of the walls. So let's take these two step by step. Var diameter = 10, height = 8, 8-foot walls. Now we can calculate the radius, which we've already done up here. So the radius is the diameter divided by 2, great. Now the formula for circumference is actually 2, times Pi, times the radius. So, let's do this, var circumference = 2 * Math.PI * the radius. Check our work and save it. Now, we have to trigger it down here, so we'll do walls;, save it. Let's hit Refresh, we now have a value for the area of the floor, and we have a circumference. Remember, the circumference is the distance around the circle. In order to get the area we'll do another variable called wallArea, and it equals the circumference times the height. Now we'll show the wallArea as our second variable, hit Refresh, we now have a wallArea of 90. In order to make this function usable we need to pass these 2 values in because not all rooms in the world have a dimeter of 10 and a height of 8, so let's modify this just a little bit. Let's come up here and let's move diameter into there, comma, and we'll put height as the second variable, so now we're going to be passing two baskets, a diameter basket and a height basket separated by a comma. So down here, the diameter basket, let's do an 8 diameter, and let's do 10-foot walls this time. And let's change our floor so it also has a diameter of 8, therefore, this is the same room. Save it, hit Refresh, we have 50 square feet for the floor, and 102 square feet for the walls. So this represents carpet, that could represent paint. Functions Calling Functions and Returning Variables So we're making progress, but we want to introduce another step, and that is s function that can be called that will actually call both of these functions at the same time, so we don't have to have a double call down here. So let's make a new function, and we'll call it materialsNeeded. Now this is something that I like to do when I start getting many lines of code, end of function, so I know what the heck that particular curly is. I'll just clean up my code a little bit and we're ready to go. Let's come in here, because we're doing a single room the diameter's the diameter, it's the same diameter used for the floor function as the wall function. So let's do a new variable called d for diameter, and it's going to equal 8. Let's do a new variable, and we'll call it h for height, and it's going to equal 10. Now let's do another variable, carpetNeeded =, carpet is going to call the floor function, floor. What are we going to send it? The floor has to have a diameter, the diameter is in the variable d. So between these we simply put a d, which stands of the diameter, which has a value of 8. We need a new variable, paintNeeded =, and this is walls, and walls has to have 2 parameters, the first one is the diameter, which is d, comma, the second parameter it needs is height, which we can see on line 18 is h. Now let's do console.log. And we'll show the carpetNeeded, and we'll show the paintNeeded as well. Last thing we need to do is call this function. We already know how to call it from the script, we just put this in here, and it works. So we've called our function. We can see from line 6 that we have 50. some-odd square feet of floor area. We can see from line 13 that we have a 102 square feet of wall area. We can see from line 23 and 24 that the variable carpetNeeded and paintNeeded don't have a value. So here's what happened, we called floor from line 20, it went up to floor, it did its little magic and it was done. Same thing with paint. What we need to do on line 6, instead of printing the floor area to the console we need to return it back to the variable, so carpetNeeded will have a value. So let's switch this to return, and switch this to return. And they're not inside of parentheses. So we'll calculate it, we'll return floorArea, we'll calculate the wall, we'll return the wallArea, save it. Hit Refresh, and sure enough there's our 50, our 102, these 2 numbers are now coming from line 23 and 24, not from line 6 and line 13, an important distinction. Now one more thing I want to do. Let's take this line and get rid of it, let's come back to our index and let's create a button. We already know how to do this, Calculate Materials, onclick, and we'll paste that function in there, save it, Refresh, Calculate Materials, and there it is in my log. HTML Inputs and their Values While this particular application functions beautifully for calculating the diameter of a room that's 8 and the height of the walls that are 10, it's not going to be very useful for our customers who have different sized rooms. So let's jump back to our index and let's add a couple of inputs. Type= number, because we want numbers in these. Now in order to access them from JavaScript they have to have an ID. (Typing) So this is going to be the distance across the room. Next thing we need is the height of the walls. We'll make another input, type= number, don't worry about the name, instead we'll give it an id=. Now because we don't have any CSS going yet I'll just put a break tag in here and in here. This should be done with CSS, but we're not focused on that right now. Hit Refresh. Now we have the ability to enter a number and enter a height, but it's still going to default to the values hardcoded in our JavaScript. So now what we have to do is figure out, how do I get the values from this input and from this input into d and h. So that's our next task, and here's what it looks like. Document.getElementById, and that's the id we typed in earlier. So this one is the distance across. So that's going to give us the id of the input, but we don't want that, we want the value that the customer typed into that, so we're going to do .value, because the value is a child of the input. Let's try the same thing for the height by simply switching this to height. So across and height, across and height, let's test it and see if it's working. When I refresh the page and I click Calculate I get a 0, 0, which is a good sign, but not the best. So let's actually put a value in here, so the Wall to Wall is 8, Height of Walls is 10, and there's my 2 numbers, 50 and 102. So now I can do a distance across of 20 feet, wall height of 8 feet, and there's my 2 numbers. Cleanup the Output So as we use our fancy new area calculator we've got some values down here that aren't very useful. Imagine walking into a store and asking for 314.15926 square feet of carpet, they'd probably laugh at you. So we need to round these. We can't round them down though because then you'd be .1, you'd be this much short. So we're going to round them up. So let's come down here to the variable carpetNeeded, and we'll do Math.ceil, and we'll wrap that function call inside of parentheses, do the same thing for the walls. Save it. Remember we had 314 and 130, we hit Refresh, so now it's rounded each of those numbers up. That's a nice, round number, but it still doesn't tell us much. So let's come down to the console.log, line 25 and 26, and let's put in some useful information. We're going to concatenate a string with a variable, which you've hopefully done before, this shouldn't be too new. So the plus allows us to hook variables to strings. So here we have a string, Carpet Needed is, and then we'll put space, sqft, same thing down here. Single quote, single quote, plus, the variable, plus, two more single quotes, space, sqft, and this is Paint Needed. Now that we've tweaked our text a little bit let's hit Refresh one more time, we'll do a 10 and a 6. Carpet Needed 79 sqft, Paint Needed 68 sqft. While calculating the paint and carpet needed for a round room is marginally interesting, what is important is what we've accomplished. We've built a function that takes one variable in and returns a variable. We built another function that takes two variables in and returns a value. We've made another function, which calls these two functions, we've also extracted information from the HTML and put it into a JavaScript variable. We've used some math functions to manipulate our variables a little bit, and we've used the console.log to spit out the data so that it's available to the user. Now in the next module we'll look at another way to get information out to the HTML document itself. So that's it for functions. Now let's take a look at loops. Exploring Loops Overview of Loops Hello, this is Paul Cheney. Let's take a good, hard look at loops. We will start with the structure of a while loop and then jump to a for loop. Next we will use a loop to extract data from elements inside the HTML. Finally, we will build a reusable function with parameters to loop through multiple HTML elements. While Loops Let's take a look at a loop that counts to 100. In this case we're going to use a while lop. Here's the basic structure of a while loop. Notice that it has four parts. Where to start, in this case the variable i is set to 1. When to end. Because we're using a less than or equal to it will finish at 100. How quickly to go. This tells the loop to count by 1's. Once the value of i is 101, the loop will end. The last part is what to do while it's running. In this case we're printing the numbers to the JavaScript console. Let's take a look at this and practice with some alterations. So here's the while loop we just looked at. We're setting the variable of i at the first, here's our condition to end, and here's our increment with what's going to happen if we refresh this page, we can see that it counts all the way to 100 and then stops, great. If you remember back in, say fourth/fifth grade, you learned about skip counting. Well the purpose of skip counting is to help you learn math, well we can make this while loop skip count for us. Instead of adding 1, let's try adding 5. We'll save it, refresh the page, and now you can see that it increments by 5, but that's probably what your teacher had you do in fourth grade, you're supposed to count, 5, 10, 15, 20. So we can modify this by setting the variable of i to 0 and that way when you add 5 you get 5. There we go, 5, 10, 15, 20. Now it currently starts at 0. If you didn't want it to start at 0 we could actually switch the order of these 2 instructions, we would then first add 5 and then print the value of i to the log. Let's refresh it, and now we get 5, 10, 15. The problem is now it actually goes over 100 before the loop quits. So another way to manage that is to put this back and to start it at 5, and now we get 5, 10, all the way to 100, which is probably what your teacher had in mind when she asked you to skip count. Now there's another thing you can do. You've heard of the old adage, two steps forward one step back. Well we can do the same thing here with a while loop. We'll start this back at 1, we'll start by taking 2 steps forward, so i=i+2. Then we'll print out the console.log. And then we'll take away 1, this is the 1 step backward, and then we'll print i one more time. So now we should have 2 steps forward, 1 step back, and then we'll repeat the while loop. So you've got 3, back to 2, 4, back to 3, 5, back to 4, so it's working for us. In this case it goes all the way to 102 back to 101, before it comes back to the while loop, realizes that i is indeed above 100, and then the while loop quits, and it moves on, in this case, there's no more JavaScript code to execute so it ends. For Loops Now let's take a look at another loop that counts to 100. Here's the basic structure of a for loop. Notice that it's more compact. However, it still has the same four parts, where to start, this is run before the loop begins. When to end. How fast to go. This is run after the code block has been executed. In this case we're using a shorthand version of i=i+1. The last part is what to do while the loop is running. Let's take a look at this one in practice. Here's the code block for the for loop that we just saw in PowerPoint. And this is what it looks like when it runs, it simply counts 1 to 100, just like the previous one. Let's do some modifications on this. Let's try reversing this so it counts backwards. So instead starting i at 1 we'll start it at 100. And instead of ending at 100 we will end it at 1. So what we'll run while i is greater than 1, and then it will stop running. So if I said 100 and we want it to go backwards, then we need to do i=i-1, or we can do i--. Save it, let's refresh, we now get 100 counting all the way down to 2. If we want it to go all the way to 1 we'd have to put a greater than or equals and then we could get it to go all the way to 1. Once again, to count by 5's you do i=i-5, that would count in reverse, starting at 100 going all the way down to 5. Accessing DOM Data So I've modified my Index.html and I've added a select called state and I've just given it four values to start with. As long as the select has an id we can access the children of it. We can access the value and we can access the text of any one of these. Let's go ahead and jump back to our JavaScript and let's start by running some tests. First of all we're going to create a variable and we're going to call it elementID. And we're going to set it equal to the document.getElementById. And the id we're looking for is the id of state. And of course we need a semicolon. Now, to make sure we're on the right track let's do console.log and let's display what we have found in elementID, save it, run it, and we can see over here on the right that we have a select with an id of state. If we open it we can see all of the children of that item, so far so good. Another thing we can do, console.log, is we can ask for the length of this elementID. Now the elementID is an array and arrays have the length or the number of children. In this case there are four children, Wyoming, Utah, Idaho, Montana. So if we ask for .length we should get the number 4 showing up in the console, and sure enough, there's a 4 because there are 4 children. And if we were to go back here and were to add another state, in this case we'll add Colorado, save it, and refresh it, the length has now jumped to 5, and we can see number 5 in our list. We now have one of the pieces of information that we'll need for our loop, let's take a look at a couple of other things, console.log, element. Now because it's an array, which simply means it's a group of items, we use square brackets, and we'll ask for the text of one of the items. So let's ask for the text of item number 1, save it, hit Refresh, and we can see it displays Utah. Well if we look over here Utah's actually item number 2, not item number 1. That's because arrays are 0-based. To further demonstrate that let's ask for item 5, which should be the last 1, which should be Colorado, and we'll refresh it, and we get an error because there is no 5 in the array. What we've actually got here is 0, 1, 2, 3, 4. So 4 would give us the value of the last item and 0 would give us the value of the first item. So here's something we can do inside of our loop, in addition to asking for the text we can also ask for the value. So in this case Wyoming, the state abbreviation is WY. Number 2, number 2, save, refresh, we now have Idaho and ID. Now we're ready to build a for loop. For open curly, close curly. What are the pieces we need inside the parentheses, well we need a starting point. So we're going to use the variable i and set it equal to 0, because remember arrays are 0-indexed, semicolon, and where do we end? Well i is less than, remember up here we know the length of the array, which is the end point. Now the reason we use less than and not less than or equal to is because the length of this is actually 5, but if we 0-index it it's 0, 1, 2, 3, 4, and that's where it stops. So i is less than the length, which stopped at 4, semicolon, and now how fast do we move up? Well we want every single item in the list so we'll do i++. Now let's take these two and we will display both the text and the value of each element by simply changing this to an i, which is a changing value, inside the for loop. Let's save that, get rid of that, let's test our work, and there we have Wyoming as the text and the value as the short postal code for each one of the items in our list. Placing Loops in a Function Now we're going to advance to the next step by adding a second select to our page. So now we have a state drop-down, and we have a Home Style drop-down. We currently have a single for loop that accesses all of the items within the state one. If we came up here and changed this element by id to home and ran our code, you can see that we get the same results, now we're accessing Home Style instead of state. Well let's turn this into a function that we can use over and over. So we'll come down here and we'll create a new function and we'll call it, showStuff. Well what pieces up here need to go into the function? Well we need to know what the elementID is, so we'll put that first. Once we know the elementID then we can go ahead and we can run our loop, so we'll put that next, end loop, end function. Got to keep this stuff straight so that we don't all lose our minds, and we may even want to indent stuff to keep it nice and clean. Let's go ahead and strip out this first batch of code we no longer need, we'll save it, run it, and nothing happens. So we need to call the function in order to see any results. ShowStuff, save it, refresh, and there's our single family. Now instead of hardcoding this elementID in here let's actually pass it as a parameter. So let's create a variable up here called element and we'll use that element here, we'll just use short el for it. Now we're going to pass in a string, let's start with home. Refresh, and there's home, no change. Pass in state, save, refresh, and there's our state. Well now we can do this, copy, paste, home, save it, and now we can use that function, which is a flexible function because it's being passed a parameter, to access either one of our selects here from our homepage. Let's now take this one step further by putting both of these inside their own function so that we can then call it with a single button here in a second. So we'll make a new function and we will call it evaluatePage. And inside this function we will run the function to call the state and the home, which runs this stuff over here. And once we clean it up it looks like this. Now if we run our page we should have nothing happening because nothing is calling the evaluatePage function, therefore nothing is calling the showStuff function, so everything is dead in the water. Let's come back to our Index, let's make a new button, we'll call this button Run Script. And when we click this button we want it to run this evaluatePage script. So we'll put that right there, save it. Refresh, there's our Run Script button, click, and here's the evaluation of both the state and the Home Style. Now that we have our JavaScript running under the control of a button we actually have the ability to make selections here and then run this script. So we should be able to come back to our script and ask which one is selected. Well it's going to be very, very similar to what we've already done, except that the word value now becomes the word selected. Let's refresh the page, let's choose Utah, and Multi-Family, and run the script. We can see that Utah now has a value of true, and Multi-Family now has a value of true. So there's yet another thing that we can check on when we loop through all the values of these elements. Finding the Selected Item So far all of the output from our function is being displayed in the JavaScript console. Let's now change that so we're actually putting it out here on the page, maybe at the bottom. So let's come back to our Index and we will add a break tag here just to make things look a little bit nicer and then we'll add a division tag. This division tag's not going to have anything in it, but we are going to give it an id of output, so that we can put stuff into it. Now let's come back here to our JavaScript and let's run a test, document.getElementById, and the element we're looking for has a name of output, and we're going to set its innerHTML equal to Hi, and semicolon. Let's save that, run it, and there's the word Hi inside our empty division. Now that we know how to access it we can change our function. If the element by id equals true then we're going to do some stuff. Let's go ahead and put this, and instead of saying Hi, let's say found me. Get rid of this one, save it, let's go ahead and refresh and run our script. So it did say, found me, so this loop is being triggered, but found me doesn't say anything about what was found. So, instead of that less than helpful message, let's put something more useful in here. When the value of any item is selected, then we can access the value and the text. So let's, inside this loop, say variable, and let's just use x = the elementID and we will get its text. Once the text has been put into the variable of x, we'll change this found me to the value of x, save it, run it, run this script, and we have Single Family. If we hit Multi-Family that now says Multi-Family. Well what about this one up here, because it's actually being checked too. Well what's happening is it's actually putting Wyoming, but then it is so quickly erasing it and replacing it with Multi-Family that we don't actually see the difference. So let's make some modifications now to our script. Our function showStuff ends right here. So let's, instead of displaying stuff here, let's actually return the value of x so we can come down here inside of our second function, and we can create a variable, and we'll call it feedback. And we're going to set it equal to showStuff for the state. And then we're going to take feedback, let's go ahead and remove this up here because it's not really serving us well, and instead of putting x inside the division we'll put feedback. We'll save that and run it, and now we get Wyoming showing up, switch it, we get Utah showing up. So the first one is working, the second one is still not quite there, but we're making progress. So let's do this, let's do variable feedbackState, and then we'll do another one, which is just like it, except it will be feedback for the home. And we will run the function home. So when we put stuff in this division we can put feedbackState + feedbackHome. Make this a little bit wider, save it, let's try that and see what we've got. We'll run our script, we get Wyoming, and then we get Single Family, we can do Idaho, Mobile Home, Idaho, Mobile Home. Well that's okay, let's put a break tag in here, and then of course we need another plus. Multi-Family, Idaho, we now have Idaho and Multi-Family. So now we're able to track with JavaScript what the user is selecting, put it into a variable, store that variable, and then at will, either display it on the screen or display it in the console.log. Before we leave let's clean up our code a little bit. We first of all don't need all of these console.log statements now that everything is working, so we can remove that. These extra spaces here can go away, we can add a comment here that says end of the if so we know what that is, remove this line, so everything now is tightened up. And of course it runs beautifully. Finding the Checked Item So we know how to use a loop to access the selected item, what about an input-type of checkbox? Here I've added a Lighting heading, and I have three checkboxes, one for Incandescent, one for LED, and one for CFL. On our web browser it looks like this. These are checkable, multi-checkable, or single, so you can select one, some, or all. What we want to do is when we run the script, in addition to knowing which one of these was selected we want to know which one of the lighting types was selected. Because we're no longer using a select with multiple options, but instead multiple inputs who have the same name, in this case bulb, we're going to have to create a different function. Let's come back to our JavaScript and let's start from the basics one more time. Let's create a variable, and we'll call it elementID again, and we're going to set it equal to document.getElements, notice the S, ByName, semicolon. And then let's do a console.log, and we'll drop the elementID inside there and see if we get anything out of it. Up here we used an element by id because it was single id with multiple children. Here we don't have that. We have three different inputs, but they all have the same name. So the name bulb is going to go into here. Save that, let's see what we get here in our output. And there are three inputs showing up. So let's add a .length, just like we did in the above function, and sure enough, we get 3 because there's 3, Incandescent, LED, and CFL, so that's going to be the same. So how do we tell now which ones are checked? Let's do a consold.log, and once again we'll do elementID, remember because it's an array we use square brackets, and we're going to ask for the checked status. Up here it was the selected status, down here it's the checked status. Well it needs to know 0 to 2, so let's start with 0 to see if that one is checked. Refresh it, and it is a false. If I click it and refresh it, it's still a false because it's reloading the page and in the process of reloading the page it is unchecking my selection. So at this point we're kind of stymied until we create this as a function. So let's wrap this whole thing inside of a new function, and we'll call it showMore, open curly, and come all the way down here for a close curly, and then a comment that says end of function. That takes all of this code and makes it so it will not run until we activate it some way. So down in here inside this function let's call it, there's our showMore function, save it. Hit Refresh, nothing, let's go ahead and click Incandescent, run it, and sure enough we get a true. If we uncheck it we get a false. So, this seems to be working. So now how do we put this inside of a loop? Because that's the whole point is to say how many of them are checked, not just to check one random one. For open curly, and end of loop. So what are the things that go inside the parentheses? Well we need to start i at 0, which is the beginning of the loop, semicolon, i is less than, and here we've got elementID.length already specified for us, so let's drop that in with a semicolon. And then of course you want to add one to it. So we'll check each one in the loop. Let's take this, cut it, put it inside of the loop, and change the 0 to an i so it's incremented, now we'll check each item, and evaluate it to true or false. Let's refresh the page, we'll do a true, false, true, boom. True, false, true. So now it's tracking it in the console, we simply need to get it out of here and over here to this. Now this is going to get a little bit messy, but hang in there with me and we'll see if we can figure it out. We have the ability to check the checked state as true or false as we loop through each of the items. In addition to the checked state being true or false, we can also check the value of each one, just like we did before. So we run this script, we have the name or the value of each, and whether it's checked or not. Now really all we want down here are the ones that have a checked equals true. So, we need to add inside of this loop an if statement, if, open, close, end if. Well what are we checking for? We're checking to see if the value of this is equal to true. Because remember we have falses and trues appearing over here. Well if it is true we're creating a new variable called mycheck and set it equal to the value, which we already know how to get right there. Now this mycheck needs to be set up initially above the for loop, so we'll come up here and we'll say variable mycheck is going to equal, and we'll make sure it's empty, so there's nothing in it. And then if something is checked we'll put the value inside there. When the if is through then we're going to console.log mycheck, and we'll see what's in there. Let's hit Refresh, run the script, and we have an awful lot of stuff over here so let's clean up a little bit. Let's get rid of these, so we'll just comment them out, comment this out, now our log should only contain the results of line 23. We're going to refresh the page, and click Incandescent, and run the script, we now have Incandescent appearing three times. Let's clear it, let's check Incandescent and LED, run it, we now have Incandescent and LED appearing two times. So this is not exactly what we're after. Because we put the console.log inside the for loop it's spitting out this value three different times and it's always spitting out whether it's checked or not, so we actually need to move it down so it's outside the for loop, so it only presents its results once. So let's try that. Hit Refresh, we cleared it, click Incandescent, notice it prints it once. If we click two of them, I'm now getting just the LED. Let's check that, run the script, sure enough, it's just the LED. So what's happening in line 21 is the value of mycheck is being replaced and not added to. So in order to get the list of all the items that are checked, we need to set mycheck equal to itself, mycheck + the new element. So now let's run it, we'll hit Incandescent and LED, and now notice that they're together, if we hit all three of them, I'm now getting Incandescent, LED, and CFL. Not very readable, so let's add a + and then a break tag. This'll make it a little bit more legible because now the results will be on separate lines, we'll click just Light, there's LED with the break, click all three, and we're getting them like that. Instead of logging this to the console let's stick it out over here. So we need to come down here and tweak this a little bit. Create a new variable called feedback for the Light and set it equal to the results of showMore. In order for that to work then we need to return mycheck, so when it comes back here it gets put into feedbackLight, and then of course we need to add that over here, + feedbackLight. Save it, go back to our browser, hit Refresh, hit Run Script, there's nothing there because nothing's checked, we'll check all three of them, and sure enough, there's Incandescent, LED, and CFL. Notice that Incandescent and Single Family are on the same line, that's because we need to add another break tag between these two, so we'll drop in a br tag, save it. Let's test it one more time and see how we're doing. Refresh, select Run Script, we've got Wyoming, Single Family, Incandescent, LED, let's make some changes. Idaho, Apartment, CFL, boom, Idaho, Apartment, CFL, but we're using both LED and CFL. This script is now replacing the contents of this empty division and refreshing it every time I click the Run Script button, based on my selections here in the HTML. In our current HTML page we only have one of these checkboxes in the page, but we can make our JavaScript more usable in case in the future we decide to add an additional checkbox type. So let's come back here to our JavaScript. Down here where we have a call on line 35, let's put the value of bulb. So now the value of bulb is going to be sent to our function, we'll bring it into the parameter called el. And we'll replace the word bulb with the value inside of el, which is short for element. Now let's run it and see if we've broken anything. Back to our browser, hit Refresh, click a couple of these, run the script, and sure enough everything is working. So that's it for loops. Next let's take a look at a switch statement. Exploring Switch Statements Overview Hey, I'm glad you're still with me because we're going to explore the switch statement. We'll start with the structure of a switch statement using strings, and then show you how you would switch on numbers. Finally we will see a fall-through switch statement. A switch statement is basically a bunch of if/then statements all glued together into a single code block. Let's take a look at the parts. A switch statement has a single variable that it checks. Each possible match is then set up as a case with a matching value. If there is a match, then the statements following the match are executed. In this case if my variable was morning, then the console would log the message, Time for Breakfast. Once a match is found there is no need to keep checking, so you break out of the statement and jump to the end. Just in case there is not a match found, you should provide a default option. In addition to switching on variables with a string you can also switch on a number. If the variable myNum is assigned to the number 3, you would be assigned to the Bear team. If the variable myNum is assigned to the number 1, then you would see an error message because myNum did not match any of the cases above. A switch statement can also have multiple cases with similar results. This is called a fall-through switch. In this statement a number of 1, or 3, or 5 will generate a message that these are odd numbers. A number of 2, or 4, or 6 will generate a message that these are even numbers. Let's try this out using the start JavaScript file from the demos provided with this module. Switch with Strings Let's begin by creating a script that converts a number to a day name. I'm going to rename the startJS to dayPractice, drag it into my editor, and we will start with the HTML. I'll change this to Day Converter. The first thing we're going to have to have is a select. We're going to have to have seven options, one that represents each day. We'll give it a value, and Sunday will be a U, it'll also be day number 1. I'll change these. (Typing) In addition to having a select with several options, we also need a button to activate our script. Instead of using the Console log, which we've done before, we're going to actually send the results back to our HTML page. So we're going to put an empty division down here and we'll give it an id. Now we can open up our JavaScript file. We need to have a function, and we'll just call it myFunction. The first thing we're going to do in this function is find out what option has been selected. So let's create a new variable. And once again, in between these quotes we need to get the id of the select. So let's jump back to the Index, we have a select, let's give it an id= chooseMe. We'll copy that exact value back to our JavaScript and put it in there so we have a connection. We'll then do a new variable, we'll call it dateShort, and it's going to be equal to the elem.options, because it's an array we'll use square brackets, and then we'll get the value of the selected option. So now we need to come back here, we've got our element, and we want to ask for the selectedIndex. Let's make sure this is working before I go any further. I'll take the dateShort and we will display it to our console. Now that we have our function in place, we will use the function name, which we have right here on line 2, copy it, return to our Index, and here on line 23 where we have onclick we'll paste the name of the function. Let's now test it and see if that's going to work. Let's open our index file, we'll inspect, switch to the Console, and click Run Script. And we have U appearing, which is day 1, which is Sunday. So Saturday, day 7, should be an S, Sunday, Monday, Tuesday, Wednesday should be day 4, and sure enough there's a W. Now that we have the Console displaying the dateShort, let's now connect so that it shows up here in the feedback division. So let's come down here and start by putting document.getElementById, the element that we're after is called feedback. So I'll just copy that to make sure I don't get any typos, and we're going to set the innerHTML equal to, and we'll grab this variable and paste it with a semicolon. Let's save that, refresh our page, run the script, and I'm getting a U and a W appearing here on the page, as well as in the Console. Now we're ready to do our switch statement. Here's the code for the switch statement. Switch, open curly, close curly. We're going to be switching on a variable, well right here is the variable, it's called dateShort. And then we need to set up several cases. The first case is going to be Sunday, which is a U, and with a colon. And then what happens if dateShort is actually a U, well, dayName = Sunday. Let's come up here, we have a variable element, we have a variable dateShort, let's go ahead and create a new variable, call it dayName. So it's defined and down here we can just assign it. If indeed the case is U, we'll assign that variable, and we're done, there's no need to continue with any other statements below it, we'll just crash out of it. Now we'll come down to line 21, instead of showing the letter of the day, we're actually going to show the full name. So let's save it, hit Refresh, run our script, day 1 does indeed equal Sunday. Now we haven't got anything else set up, so I'll do that next. The entire code block for this switch statement is found in the demos for this particular unit, so you don't have to type it out by hand if you don't want to. I'm just going to paste that in, notice that Sunday is exactly the way had it, we've simply included Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and we've included a default value, in this case it says the dayName is Out of Range. Let's save that, refresh our page, let's try a different day, we'll choose 4, and it's Wednesday, 7 is Saturday. So we've now successfully converted a string, in this case, a single letter of the alphabet, to a full name of a day of the week. Switch with Numbers So let's continue with our existing code and simply switch the K statement from letters to numbers. Up here at the top we are interrogating the drop-down element and asking for the selectedIndex, and we're getting the value. Now remember the value is represented right here as a string. But there's also the number 1, the number 2, the number 3. We can change this from value to text. And now let's see what the Console log is going to give us. Let's refresh it, run the script, the Console log gives us a 1, gives us a 3, gives us a 7, so we are getting 1, 3, and 7, but our switch statement is broke, of course, because the values are no longer U, M, T, they're now 1, 2, 3. So let's just come over here and put a 1, and a 2, etc. Let's save it, refresh the page, run the script, and we're still getting an Out of Range error. So it's still coming down to the default value even though I can clearly see a 1 and a 4 in my Console log, it's not working as a number. Well here's why, this .text is pulling the text as a string. So even though it looks like a number 1, a number 4, it's actually a string with a 1 in it and a 4 in it, so the variable dateShort is a string. So we need to force it to be a number. So we need to convert this variable dateShort from a string to a number. So we'll simply put Number, left parenthesis, right parenthesis, move dateShort inside of that, save it, hit Refresh, run our script, and now we're getting Sunday from a 1, number 5 gives me Thursday, 7 should give me Saturday. Now just because in my switch statement I've got my case 1, 2, 3, that doesn't mean that's how they have to be. I can move these cases anywhere in any order and they're still going to work. So I could start with 3, and then go to 1, and then 2, I can move 6, let's test it, 1 is still Sunday, 2 is still Monday, 3 is still Tuesday. While it's possible to put these cases in any order, sometimes it makes better sense to keep them in order because your day of the weeks are going to make more sense if it starts with Sunday and ends with Saturday, then if you have some spaghetti code where things are just randomly thrown in here. Switch with Fall Through Now let's make a switch that has some fall through. Let's go back to our Index file and instead of having days 1 through 7, I'm going to change this to Fortunes 1 through 10. Now the code for this select is provided in the downloads, so I'm just going to copy it and paste it. We have now have Fortune 1 through 10 with values matching 1 through 10. Let's go back to our JavaScript file. Line 3, it's fine the way it is, we're no longer getting a dateShort, we're getting a fortuneNum, and we'll grab the value. Instead of dayName this will be fortune, and let's clean this out. So the fortuneNum we want to drop into the Console to make sure it's working, and then we want to switch on a number, not a string, of the fortuneNum. So let's save that and let's put in our first case. If the user chooses a 1: then our fortuneMessage is going to equal You will inherit a fortune;. And we're done so we're let's break. Let's test it to see if it's working, run my script, and we can see in the Console that line 19 has an error because dayName has not been defined. Well I changed it from day to fortune. So let's take the fortuneMessage and display it in our div, hit Refresh, try it again, I get a 1, and I get a You will inherit a fortune as my message. Case 1 is inheriting a fortune, let's do case 3 as well. So if it's a 1 or it's a 3 they're going to inherit a fortune. Let's refresh, Fortune 1 and 3 are both a fortune, great. Let's copy this, let's do 2 and 4, maybe they will win a new car, that would be nice to have, and of course we need to break. Save it, refresh, let's try 2, there's the new car, let's try 4, that's also the new car. So the fall through in this case is that the 1 or the 3 give me this feedback message, the 2 or the 4 give me another feedback message. Once again, I've provided the entire switch select in the demos for this unit, I'm going to paste the completed code, I've still got fortuneNum cascading all the way down through, I'm setting the fortuneMessage, which is displaying down here on line 34, let's save it, see if everything is matching, refresh the page, run the script, You will inherit a fortune, let's try number 4, got a new computer, number 8, 8's also a computer, 10, you've got 3 hours to live to finish this course. So that's how a fall-through switch statement works. So that's it for a switch statement. Now let's explore interrogating the DOM. Interrogating the DOM Overview Hello and welcome back. We're getting really close to the solar calculator, however, before we get there we need to review how to access elements in the DOM. We will start by getting and changing text using five different methods of interrogation. Then we will use a combination of these five methods to refine our interrogation techniques. The first one will be GetElementById. Notice that the word Element is singular. This tells us that it returns a single object. Second, we will GetElementsByTagName. Elements in this case is plural, so we'll get a collection of items that we access using array notation. Third we will use getElementsByName, which also returns a collection. Next we will use getElementsByClassName, again, a potential collection of multiple items. Then we will use querySelectorAll, which is really awesome, and also returns a collection. Finally, we will combine these to really target our inquiry. Make sure you have the starter file from this module's demos, it contains lots of HTML code that we will be using. Let's get started. Element by Id Here on my desktop I have the startFileModule5, which contains an index file, a CSS folder, and a JavaScript folder. I also have the demos.txt, which is a file that contains lots of source code that you can copy and paste while we're moving through these modules. Let's take a look at, in my case, Sublime Text, here is that startModule5 that you see over here to the right. You can see it contains a CSS folder and an almost entirely empty CSS file. It also contains a main.js, which is entirely empty, and then of course, the Index file. Let's take a look at the Index file, this time in Chrome, I've got my JavaScript Console open on the right, and I can see the HTML document on the left. The HTML is a standard web page with the four basic parts. The first part is the header, which contains an h1 and h2. Then the second part is a nav, which contains an unordered list with a bunch of list items. We then have the main, which contains several sections. Each of the h1's is correlated with one of the main menu items, and you can see the link here is a paneled sign, which references this id. So it's a single-page website, which simply scrolls down to the relative spot. This first h1 has a couple of h2's with paragraphs, notice that they have names, we'll use those later on. The second h1, Exploring Functions, has a list. The third one also has an unordered list, and the fourth one has an unordered list. The fifth section, Document Object Model, has a form with three inputs, each with a name, which we use later on, and a select with three options, which we'll also use later on. The final piece of the web page is the footer, this case it has a class called smallCenter. Let's go back to our main JavaScript file, and let's start by targeting an element by id. So we're going to create a new variable, and we're just going to call it foundYou, and we're going to set it equal to the document.getElementById. Notice in this case that Element is singular. Now let's go back to our main file and let's pick a section. Our first section's called overview. Down here on line 28 there's an id called overview, so let's target that one. I'll just put it here between the quotes, and now let's see what we've found. Console.log, foundYou, and I've got to fix that typo and that typo. We'll save it, let's refresh, and we can see over here that the h1 with an id and overview, that's what's found is the single element and it's now being displayed in our log. Well now that we've found the variable let's take a look at just the text that's inside of it. So we can do console.log, foundYou.innerText, and of course semicolon. So we'll save that, refresh it, and we can see that gives us the text that's inside of that. So here's Overview and there's Overview accessed using JavaScript. Well great, now that we have the text let's change it. So foundYou.innerText =, and I'm just going to make it really obvious here, I changed You, with a semicolon at the end, save it, hit Refresh, and we can see that there's the change made inside of our HTML document using line 6 of JavaScript. Now quick side note, we have innerText, we also have HTML, so we can change that as well, and that's another way of accessing and changing stuff. And the results, as you can see here, are identical. Element by Tag Name The next one we're going to try is accessing elements by tag name. Now the tags on this page, there's lots of them. We have h1's, h1's, h1's, we have a couple of h2's, we have some paragraphs, and all of those can be accessed using ByTagName. So let's jump back to our JavaScript, start off with a variable, once again we'll use foundYou = document.getElements, with an s, ByTagName, in here we simply list the tag name we're looking for. Let's start by looking for all the h1's. And then we'll console.log, and we'll put foundYou in there, and see what it comes up with. So let's save that, hit Refresh, in here we can see h1, h1, h1, there's all kinds of h1 in a collection. Because it's a collection we can use array notation to access them. So we'll do a console.log foundYou, left, right, and we can put a number in here. Any number that's less that the total number in the collection, so there's lots of h1's, so let's just put a, say, 2 in there. Save it. So there's the second one, Exploring Functions. Well we can also ask for the .innerText of this second item, which actually the third item because it's number 2, and now we get Exploring Functions, which matches this, Exploring Functions. And if we were to tag number 3, of course that would be Exploring Loops and Exploring Loops up here, those match. We can also look for all the paragraphs, hit Refresh, and we can see a collection of paragraphs. We have an error here because, as you can see, there's 1, 2, 3 paragraphs, which would be numbered 0, 1, and 2, but we're asking for number 3, which doesn't exist, so let's back this off to 1. Try it, and sure enough, we now have the entire content of paragraph number 2, which you can see there and over here. Let's go back and do 1 more thing, foundYou, array notation, let's do the second item, which is array element number 1.innerText = I Changed You. Save it, hit Refresh, and we can see the results here, under Abstract the paragraph has been changed and replaced with the text from the JavaScript. Element by Name Now let's try accessing elements by their name. So, we'll start with the variable foundYou = document.get, notice the s on Elements, ByName, and we'll fill that in here in just a second. So let's jump back to our Index, here we have a name associated with this paragraph on line 30. We also have this same name associated with the paragraph on line 33. If we go down to the bottom, 70, 71, and 72 also have names, in this case they're unique, first, last, and phone. So we should be able to go to our JavaScript and put first in here and then be able to track the results in our console.log, save it, refresh, we can see that there's an input that it has found, and notice that is a list, a collection that says NodeList here and it has 1 element in it, because there's only 1 with the name of first. Now let's try description. Remember that was the paragraphs, this paragraph and this paragraph. Refresh, we now have a NodeList with 2 items, paragraph 0 and paragraph 1. In order to access the content of those because it's a collection we'll use array notation and ask for innerHTML or text, in this case let's start with the second one, hit Refresh, and there's the text from 1 or the second element in the array. Of course, changing that to a 0, which show us the first 1, and there's that. Once again, now that we've found something we can change it. FoundYou, which one are we after, well let's do the first element and set the innerHTML to equal semicolon, and I forgot the dot right there, there we go. Save it, hit Refresh, and here we can see the results of our JavaScript acting on the first element of the foundYou collection. Element by Class Name Now let's take a look at accessing something by its class name. So in our Index page, at the very bottom, in the footer, we have a paragraph whose class is smallCenter. Let's go back to our main JavaScript page and let's access that one using a variable, foundYou = document.getElements, plural, ByClassName. And the class name that we're after is smallCenter, so copy that, paste it in here, and then we'll do a console.log, foundYou. Save it, hit Refresh, and there it is, it's a paragraph whose class is small and center. Because there's only one element, when we access the array notation it's going to have to be 0, but then we can ask for its .innerText, or innerHTML, and we can see the footer matches the text that we found. Once again we can change it by taking this and setting it equal to New Paragraph Info, save it, and there's the new footer paragraph at the bottom of the page. Query Selector All Now let's take a look at the querySelectorAll. This one is my favorite. Variable foundYou = document.querySelectorAll. Now we can look for any selector we want, so let's start by looking for all of the list items on the page. Then we'll do a console.log, foundYou. Save it, take a look at it, and we can see there's a lot of list items, 1, 2, 3, 4, 5, 6. So every single list item from Overview, Functions, and Loops, down to all of these, down to all of these, including all of these. So those are all list items that are showing up over here. Because it's a collection we can read an individual one. So we'll do array notation here, let's grab the first one, ask for its .innerText, save it, and we get Overview from the first item in our list. We can also change by setting the value equal to some string, save it, hit Refresh, and we can see that that first menu item has now been switched to just text instead of a link. Let's now move on to look at a little bit more specific use of the querySelectorAll. It can not only find individual list items, as we have here, but we could look for an unordered list with a specific id. In this case let's go back to our Index, and scroll up, and let's target this list of items, there's one, two, three, four, five, six items in our function list, and here is the id. So let's jump and put an unordered list who has an id of fn_list. Let's save that, hit Refresh, and there's all of the text in that element. Now this is a little bit confusing, so let's track the length of what's being discovered here so it'll help you understand when we move on to the next phase. Let's reveal the console.log and let's get the length of foundYou.length, and we'll make it a little bit more clear here by adding something in front of it, LENGTH OF COLLECTION. Let's save that, hit Refresh, and we can see the length of the collection is 1 because it has found the unordered list. But, if went in here and we add a space, which means a child of, and now ask for all the list items, we're now getting a LENGTH OF COLLECTION of 6 because there's 6 items in this Exploring Functions unordered list. Now we've chosen to change element 0 of the 6, which you can see the results of right here. But if we wanted to change number 5 we can see that it's now moved down here to number 5. Well what if we wanted to change number 2? There it is in the middle. Now, we've messed with Exploring Functions, let's go down a little bit and simply change this to a different id, we're now under Loops. Change that, we're still going to look for an unordered list, we're still going to ask for the list items in that unordered list, and now it's moved down to here under Exploring Loops. Combination 1 Now let's use a combination to do something similar to what we just did with the querySelectorAll. We'll do a variable, foundYou, and set it equal to document.getElementById. In this case we're going to get the sw_list, and of course we want to track it so that we can see what we've got. And there it is, an unordered list, we can see here it has three different items. Now we're going to get all of the children of this foundYou element and put them into a collection. So we'll set up a new variable because this next one is going to be a collection, I'm going to call it childArray, and I'm going to set it equal to foundYou.getElementsByTagName, and we're going to look for the list items inside of this unordered list, which we can see right here is the result of the id. And of course we want to track that. Let's hit Refresh, and we can see that the second Console log is a list of three items in a collection. Now that we have the childArray, let's go ahead and change the innerText of all three of those elements, childArray, element 0.innerText = These Items. Don't forget the semicolon, copy that, do it 2 more times, a 1 and a 2 Have Just, Been Changed. Save it, then refresh, and there's the results and our switch statement of our innerText statements. Combination 2 Down at the bottom under Document Object Model we have three inputs. Underneath that we have a drop-down, which currently says, Honda, Chevy, Ford. We're going to use JavaScript to change the options of these to colors. So let's go back to our JavaScript and we'll start by setting up an array of colors because we're going to be using a loop. Let's start with a variable called newOptions, and we'll set it equal to an array collection, quote, comma, quote, comma, quote, and we'll put three colors in here. Next we will grab the ElementById of the form. So we'll set a new variable called foundYou and set it equal to document, Element singular, ById, and let's go grab the id from our HTML, myForm. Save it, console.log, foundYou. Now let's see what that gives us so far. Sure enough we have a form, we can see that that form has one, two, three inputs and a select. In our case, we want to target the select. So we'll break this down further by doing another variable, and this is going to be a collection, so I'll call it the selectArray, and we'll set it equal to foundYou.getElements, plural, ByTagName. The tag name we're after is option. And we can see right over here, there's our three options that we're trying to get. Let's track those in the console, and sure enough, there's our 3 options, length of 3. Now that we have those in a collection let's go ahead and use a loop this time. For, the 3 parts of a loop are the starting point, i=0, then the ending point, i is less than, selectArray.length;, and then how quickly to advance? Well we want to advance one at a time. Let's start with the first element, selectArray, and inside the brackets we're going put this i, which is changing value starting at 0, and then 1, and then 2. And we want to set the innerText equal to, and this is not where we're going to end, let's just put, it worked, for now. Let's hit Refresh, and you can see I have three it worked down here in my drop-down. We don't want that, we want it to be Orange, and then Red, and then Blue. So we're going to access this array using the same value of i. So it'll be newOptions, and it's an array, and we'll start with 0, and then go to 1, and then go to 2, see if that worked. We got Orange, Red, and Blue coming from our new options, Orange, Red, and Blue. Combination 3 Our third combination is going to allow us to access the values that the user types inside of these three inputs. Normally those values would be entered by the user and when the page is loaded they would be empty, but for the purpose of speed I've prefilled those in my HTML by providing a value= for each one of these three inputs. And so let's go back to our JavaScript and let's start with a variable, foundYou, set it equal to document.getElementById. In this case we're looking for myForm. Let's track our progress and see what we've got. So we have a form showing up here, once again, first, last, phone, and the select, we just want the three inputs, so let's further refine it by setting a new variable, and we'll call it selectArray because it's a collection, and we'll set it equal to foundYou.getElements, plural, ByTagName. The tag name that we're after is called input because we want these three inputs right here. Save that, hit Refresh, and here we can see the results of this selectArray. Once again let's do a loop. We'll put in where to start, so i=0;, where to end, i is less than, and how quickly to move forward. We'll now do a console.log, we'll grab our selectArray, and we'll increment through each element using i, and we'll ask for the .value. Where does value come from? Well if I go back here I can see that each input has a value and we'll be looking for Tim Oswald and a phone number. There we go, Tim Oswald and a phone number being extracted from each one of these inputs and displayed to our Console log. So that's it for interrogating the DOM. Let's take everything we've learned so far and build a solar calculator. Solar Calculator Overview Congratulations on making it this far. It's time to put everything we've learned together to build the solar calculator. We'll start by looking at the flow of the JavaScript program, and then we'll actually build the calculator. There are three things we need to get from the homeowner. First is how much electricity the home uses on average. This is calculated in kilowatts per hour. Second is how much sunlight they typically receive per day. Finally the homeowner needs to choose a solar panel. Each panel generates different amounts of energy. Solar panels are rated by how many watts they generate per hour, which is different than the kilowatt rating used by the home. So let's take a look at the program flow. First we gather the last 12 months of power usage from the form inputs and add them together, then we divide by 365 days, and this gives us the average kilowatts used per day. Next we find out what zone the homeowner lives in and get the number of hours of sunshine per day. Then we divide the home's daily need by the number of sunshine hours to see what we need to generate per hour. Then we have to adjust for bad weather that blocks the sun, so we increase the need by 25%. Then we multiply the kilowatts needed by 1,000 to get watt hours, remember this is how panels are rated. Then we find out which panel the homeowner would like to use. This tells us how many watts that panel can generate in a single hour of sun. Finally we divide to see how many panels are needed to offset 100% of the electrical needs for the home. Let's see this in code. Calculate Home Usage Make sure that you have the SolarStart folder from the demos for this particular unit. I'm going to open up in Sublime Text, I've got my Index and my JavaScript file open, as you can see the JavaScript is completely empty at this point. We're going to start by calculating the total annual usage for this particular home. You can see here in the Index file that there is an input for January, February, March, all the way through December. I also have assigned a value, that's a testing thing only. Once I'm done building this form I'm going to take those values out so that when the user sees it each of these is empty. But for now I don't want to enter 12 values every single time I test this page, that would drive me absolutely insane, so I've provided some defaults. On line 30 you can see that we have a fieldset, it has an id. So the first thing we're going to do is get element by id. Once we have that then we're going to access all of the inputs as an array, so there's 12 of those. So then we use getElementByTagName to put those in the list. In our JavaScript we're going to start by creating the four variables that we're going to need. We have an annual kilowatt usage, which will then be converted to a daily kilowatt usage. We're also going to have a variable i and a variable x, which we'll use in a minute. As I said earlier we're going to do getElementById, and then get the tags within that. The element name was monthly power consumption, or mpc, and the tag that we're looking for is input. Now let's track it and see if we've got it correct. After saving it we'll hit Refresh and we can see an HTMLCollection here of the 12 different elements in that array, so, so far so good. So here's the basic structure of our loop. We're going to start i off at 0, we're going to go to the length of the months, which we saw over here was 12, and then we're going to increment 1 at a time so we get every single month. Now we're going to use that variable x and we're going to set it equal to months. Because it's an array we'll use a square bracket, i.value. In this case, months i.value's going to return a string, we need to now convert it to a number. So we'll start with Number, wrap it in parentheses, and end it with a semicolon. Now that it's a number we can use our next variable, which is our annual kilowatt usage and we're going to do += x. That's the same as annualUseKw = annualUseKw + x. When we're all done, let's do a console and we'll track the value of our kilowatts. Let's save it, refresh it, and we can see that 9631 is the sum of all these months. So now that we have our annual kilowatt usage, we can convert that to daily kilowatt usage, and up here is that variable, so I'll copy it and paste it, and I'll simply set it equal to the annual usage divided by 365 days per year. And now let's display the daily usage to the console to make sure that's working correctly. So let's refresh, and there it is, 26.38 is our daily kilowatt usage for this particular set of values. Now that that is working let's wrap it inside of a function, and we'll call the function addMonths, so it describes what's happening. Open curly, and we'll close it down here. If we run it now nothing's there because the function is not being called. So let's come down here a ways and let's call the function, save it, refresh it, and now it's being called. Well here we have a hard-coded value for getElementById. But instead of using that we're going to pass the value from the function call. So let's take the name of this id here, I'll remove it, then I'll put it down here in the function call. That means in line 4 where we add months we have to bring in the name of the element, and I'll just make up my own word called elem. Once this has a value we can then use that value here in our getElementById, and that should give us the same result, and there is, once again, 26. Down here let's create another variable called daily use in kilowatts, and we're going to set it equal to the results of this addMonths function call. Well that means that instead of displaying the daily usage out to the Console log, which doesn't go anywhere, we need to return that value. So now if the function is done it will return daily kilowatt usage and it will assign it to dailyUseKw. And to test it we need to now console.log. I'm going to remove line 7, it was just there for testing purposes, and I'll reuse it down here to display the dailyUseKw. Let's save it, refresh, and now we have just the results from line 27, which we can see here. So to clean this up a little bit, our first function to add up the months is complete, it returns the value of daily kilowatt usage and we have that value now assigned to a variable, which we can use later in our master calculations. Calculate Number of Sun Hours The next piece of the puzzle is to gather the amount of sunshine used from this Sunshine Zone graphic, and the user selects the zone that's appropriate to where they live. If I lived in the state of Florida that would be Zone 4. Here in our HTML we're going to access the zone that is selected by the user. So let's take a look at the drill-down for this. We'll start with the document. The document contains a form. The name of this form, and actually the only form, is called solarForm. And then if we scroll down we can see that we have a select, which also has a name called zone. And then we're going ask for the selected index, in other words, which one of these is currently selected. In our JavaScript let's come down and create a new variable, and we'll call it theZone, and we'll set it equal to document.forms.solarForm.zone.selectedIndex;. For part two we're also going to need a variable and we'll just call it hrs, which stands for the hours of sun. TheZone is referencing a selectedIndex, which if you remember from our previous units is an array and starts at 0. But if they choose Zone 1 I don't want to return a 0, that doesn't make any sense, I'm going to offset this by 1, so theZone +=1. So now, if they choose a Zone 1, the value of theZone is 1 so we have an even match. Now we're going to use a switch case to convert the zone number into hours of sunshine. So we're going to switch on theZone, and let's go ahead and set the first one up. So let's start with a case of 1. If they've chosen Zone 1 then the hours of sunshine is equal to 6. And since we found a match we'll just go ahead and break and jump out at the switch statement. If it's not Zone 1 let's do a case of 2. Once again, we'll assign hrs equal to, in this case 5.5, and we're done. So here's all the rest of them in the switch statement, Zone 1 all the way through Zone 6. Now the default, if for the some reason something goes wrong we'll just assign hrs to 0. But because it's a drop-down it's virtually impossible for them not to choose something. And when we're done let's console.log the value of hrs, save it, and we can see that Zone 1 is the selected index and it's returning a value of 6. The problem is choosing a different zone we now need to activate the JavaScript, and we haven't got a button set up to do that yet. But what we do want to do is take this code block with the switch statement and turn it into its own function again. So we'll make a new function, I'm going to call it sunHours, and we will end that function down here with an end function. Now instead of doing a console.log, which, once again goes into oblivion, we'll return the value hrs, and then we need to come down here and call it. Here on line 52 we'll create a new variable, call it sunHoursPerDay, and we'll set it equal to the results of this function call, which is sunHours. We're not going to pass anything, but we do want to do a console.log and show the sunHoursPerDay to make sure that it's working correctly. We'll save that, hit Refresh, and notice now that we have a 6 showing up, after we have the daily kilowatt usage showing up. Now let's hook up this Calculate Solar Needs button so that we can actually change the zone and make sure that we're getting the results here in the Console log. Let's go back to our main.js. I'm going to wrap these function calls inside of their very own function, then we'll call it calculateSolar, and it will end down here. So when we run the calculateSolar function it will find the dailyUseKw and it will find the sunHoursPerDay. Let's jump back now to our HTML. Here on line 74 we have a button, and when the user onclicks we're going to run the calculateSolar function. Let's save that, take a look at it, nothing's over here on the log, click the button, and sure enough it works. Change the zone, Zone 4 gives us 4.5 hours of sunshine. Zone 6 we only get 3.5 hours of sunshine. Additional Calculations So at this point we have the months being calculated from this series of inputs, we also have the sunshine per day being calculated from the user's choice. Now we need to run some calculations on the back end. Let's jump to our main.js file, down here in the calculateSolar function is where we'll make this happen. We have the dailyUseKw so we know how much energy is needed per day. We also know how many hours of sunshine per day, which is a value between, say 3 and 6. We need to divide those in order to get the minimum kilowatts needed. So let's create a new variable, call it minKwNeeds, we're going to set it equal to the dailyUseKw, and divide it by the hours of sunshine per day, and of course we want to see the results. So we'll do another console.log, and we'll take this minKwNeeds, and paste it out, hit Refresh, choose Zone 3, and we can see here that the minimum kilowatt needs is 5.277. Now remember that there are days when there's clouds and there's days when there's snow and rain, so we can't generate just 5.277, we have to increase that by 25% in order to account for bad weather. Let's create a new variable called realKwNeeds, and we'll set it equal to the minKwNeeds, and multiply it by 1.25, which is an increase of 25%. And then we want to do a console and we'll show the real kilowatt needs in our log. Refresh it, this time we'll choose Zone 1. We can see that 4.397 KW increase by 25% is now 5.49 KW. Well in order to compare the home usage, which is in kilowatts to the panels, which are rated in watts, we need to multiply it by 1,000. So our next step here is to create a new variable and we'll call it realWattNeeds, as opposed to kilowatt needs. And we'll take our realKwNeeds and multiply it by 1,000 to get the realWattNeeds. Once again we'll do a console.log and we'll paste that the realWattNeeds in there so we can see it in the log. Refresh, choose Zone 2, we can see that the 5.99 KW is now equal to 5,996 W. Choose the Solar Panel Now this next part is a little bit tricky. What we need to do is figure out which panel the user has selected and the number of watts per hour that it generates. So over here in my select on line 65 you can see I have 3 options, the name of the panel, but then the value is actually the watts that are generated by that panel. So this first one generates 250 W per hour. The second one generates 275 W per hour, and the third one generates 260 W per hour. So let's access this panel inside our JavaScript. Above the calculateSolar we'll make space here for another block of code. We'll create a new variable called userChoice, and we'll set it equal to the document.forms.solarForm, by name, panel, which is panel here, and then we'll ask for the selectedIndex, which is going to give us a 0, a 1, or a 2, and it will put the userChoice into this variable. Next we need to extract these options into their own array. Put a new variable called panelOptions, and we'll set it equal to the document.forms.solarForm.panel, but instead of selectedIndex we're going to do options. So now we need the two parts, there's the watts generated and then there's the name of the panel. So we'll create a new variable called power and we'll set it equal to panelOptions.value. And the panelOptions is an array, and so we'll use the userChoice variable to pull out the value of the correct one. The next one is very similar. This time instead of power it's the name of the panel, and instead of the value it's the text that's inside of the select. Finally, we'll put those two together inside of their own variable. So variable x is going to be equal to an array. This array is going to have two things inside of it, the power generated, comma, and the name of the panel, Console.log, and let's see what x gives us. Save it, refresh, and here it is, 250 W and it's the Axitec panel selected. Now once again, because it's not inside of our function calls when we hit Calculate Solar, that doesn't refresh. So we need to wrap this thing inside of its own function. I'm going to call this function calculatePanel, I'll come down here and I will end it, clean this up a little bit, and instead of logging out the value of x I'm going to return it. Well return it to who? We need to now call the calculatePanel. So let's come down here, inside of our master calculateSolar where we've called all of these other functions, come down here, we'll create a variable called panelInfo, and we'll set it equal to this calculatePanel function, so the value of x now is going to be put into panelInfo, remember x is an array, it has two values inside of it, a power and a name, so we need to extract those into their own two variables. So variable, panelOutput is going to be equal to the panelInfo, and we're going to get the first element, which is 0. Second variable called panelName, we'll set it equal to panelInfo, because it's an array we'll get the second value, which is 1;. And now we need to console.log both of those to make sure everything is working correctly, save it, and hit Refresh. Let's choose the Canadian one, there's the Canadian name and it generates 275 W. We choose the first one, it's a 250 W panel, and there's the name of the panel. Now that we have the real watts needed, and we have the panel that's been selected by the user, we can do some math to find out how many panels are needed for the total home. So let's create a new variable, we'll call it panelsNeeded, and we'll set it equal to the realWattNeeds, and divide it by the panel's capacity, which is panelOutput;, and let's do a console.log and find out what the result is. Save it, switch to our browser, calculate our needs, and we can see that it requires 21.9885 panels to run this house. Well, no one's going to sell you .988 parts of a panel, so we need to round it up. So we can take this calculation right here and wrap it inside of Math.ceil, and then close the parenthesis there. Now save it and refresh, we can see that it's been upped to 22 panels for the home. Provide Feedback to Customer In our HTML page we're going to replace this information using JavaScript with the results of all of the work that we've done. So the best way to do this is to first of all write out a script without any variables in it. So here's mine. I've created a variable called feedback. Notice I'm using += so it adds to the script each time. So line 1, Based on your average daily use of kWh, and this is going to be replaced by a variable, you will need to purchase, once again, a made-up number, 99, and then the brand of the panel to offset 100% of your electrical bill, fine. And then we're going to throw in an h2. We're going to throw in another paragraph. Your average daily electrical consumption is, and this is a made-up number, but we know how many kilowatts per day because it's up here. Same thing, average sunshine per hour, we know the number of hours from our switch statement. We also know that based on clouds and rain we need to increase this by 25%, so we'll show them that there. And then we're going to say, finally, The NAME of the panel, which is the name that they selected, generates so many watts per hour. And then we're going to take all of that feedback and we're going to drop it as the innerHTML of the feedback id. So let's save that, let's refresh, calculate, and here's our nonsense data right now. Fits beautifully on our page, it just doesn't have the correct information in it yet. Let's start by replacing this average daily use of so many kilowatt hours. Let's get rid of the x's and we'll put a quote, and then a ++. And between the ++ is where the variable goes. So based on your average daily use of, in this case it's dailyUseKw, save it, refresh, calculate, and there it is, 26.38, whoa, I don't think anybody wants to know that level of detail, so let's round that thing math, Math.round, and we'll take that variable and simply wrap it inside of parentheses. Save it, refresh, and now we can see it's a normal 26 kWh. Next thing is the number of panels. We've calculated that. So let's delete it, quote, quote, ++, between them we'll put the variable, in this case it's panelsNeeded. We also need to replace the brand, which is the name of the panel. So delete, quote, ++, and between it let's sandwich the panelName, save it. Refresh, Calculate, so now we can see we've got 26 kWh, you'll need to purchase 22, and there's the name of the panel, just the way it came off of this descriptor right here. So if we chose the Canadian ones, it takes 20 Canadian panels to run your home, and if you chose the third one, it'd take 22 of those. So, first part is done, now we just need to come down and do this same thing with these additional details, the process is exactly the same. Your average daily electrical consumption, well we'd delete that, put in quotes, put in a couple of pluses, in between them we'll put the rounded value of the dailyUseKw. Now we're looking at the average sunshine per day, which is generated from that map, quotes, ++, paste, sunshine hours per day. The value when increasing by 25% is the rounded value of realWattNeeds. The name of our panel is panelName, the watts generated is panelOutput. Save it, refresh it, and I've got an error in there somewhere. Oh, the two pluses here on line 92, save that, try it again, there we go. So let's choose the Canadian solar panel, calculate it, and here's all of our nice information, average data use with numbers instead of empty placeholders. At this point we no longer need all of this log information, so we can come back and comment out. I think that's all of them, let's hit Refresh, sure enough, there's no more data spewing out here on the Console log. We also need to return to our HTML page and set all of these values, which were predefined, to 0, so that the user enters their information instead of working with these values that they might get confused as important. So we'll strip out that, that should return everything to its default state. So these are all empty, Zone 1, so I would now have to completely fill these out with my own numbers, I would have to choose my zone, I'd have to choose my panel, click Calculator, and it would work beautifully. Well that concludes this solar calculator. Thanks for working through these hands-on activities with me as we have built this web application together. And look at everything we've covered. Hopefully you can use it to build something awesome in JavaScript. Course author Paul Cheney Paul Cheney is a professor of Web Design and Development at Utah Valley University, where he teaches Responsive Design. He also owns his own web design company, which allows him to keep current in... Course info LevelBeginner Rating (45) My rating Duration2h 6m Released21 Dec 2016 Share course