You are on page 1of 23

Ch_3

Chapter 3

Forms and Basic JavaScripts

Page 1 of 23

Ch_3

Chapter 3
Forms and Basic JavaScript
Overview
We have created some base pages already. We have also styled the pages
somewhat with some basic CSS and we've thrown some simple JavaScript into the
mix but with not interactivity yet. In this third session, we are going to extend the site.
That's quite logical. We're going to make some changes to the navigation of the site,
as well as allow the users to place an order for furniture using a form. In this session
we'll spend some time creating that form which uses all the new additions added to
HTML5 which make it easy to manipulate user input. Let's start by taking a look at
the agenda for this session. Firstly, we are going to create a form for the checkout
procedure for our site. HTML5 comes with a lot of new input types. And we'll use
these to create a better experience than what was possible with HTML before. In the
second part, we'll look at some other new options we have in HTML5 to validate user
input. Again, with the purpose of making sure that the user gets the best experience
while working with our site. When we will have reached the end of this module, we'll
have created a menu inside a nav block clearly indicating what makes up the
navigation for our site. We'll also have created the checkout page, on which we will
use the new input elements that come with HTML5 out of the box. And not only are
we going to use the new input elements, the page will use the new validation
options, which come bundled with HTML5. So by the end of the session we'll have
another functional page added to our site..
Creating the Contact Us page
Let us first take a look at the end result of our checkout.html page.

Page 2 of 23

Page 3 of 23 . It is a good practice to draw up the mock up because most of the time we do not have the luxury of looking at the end product.Ch_3 The following is the mock up that I have drawn.

Ch_3 Page 4 of 23 .

Skip the one contained in the red block.Ch_3 Building the Skeleton for the Checkout. Page 5 of 23 . 1. create the skeleton based on the predecessor. Once you have finished. this is what the following should look like.html Based on the mockup.

In this part we'll see how HTML5 changed this. and we'll soon start the creation of the checkout page. HTML5 has a lot of new input types. incorrect Page 6 of 23 . that's for sure. such as his name. indicating that he made an error. we are still using input and then at the type. First let’s take a look how forms is being made. He won't have to wait while the page is sending the data all over again. only allowing the user to pick a value. is an entered email address really an email address? HTML5 introduces many new input types which can make sure that the data entered by the user is of the correct type. The checkout page the user has to enter a lot of data. But there are quite a lot of things we can already check. It is for this type parameter that a lot of new options have been added to HTML5. address.Ch_3 Once done. They are indeed input types. Let's start by taking a look at these new input types. we'll take a look at some of these in a bit more detail. his email. When entering data in a rep form. So as the developers of the page we should try to guide the user in entering valid data. Some are there just to make the input of data easier by. email. So I said. On this line here. telephone number and URL for website addresses. Dates are probably the defect standard where users of a site and through all kinds of. search. let's say. you can see a list of new HTML5 input types. date. In the next couple of slides. Inside the form element. we could then add input elements which allow the user to enter data and later send that data to the server. We now have color. it's important that we guide the user while entering data. range. Is the date entered by the user in the correct format? Or at least a format we can use later on on the server site? Or for example. the user won't be presented with errors. Note that not all of these new input types add validation. Now what is valid data? On the client we don't know all the business rules so we can't check everything. and much much more. We've had the ability to post data in HTML for a long time through the form element. Making sure that the data is right from the first time takes away a lot of frustration. If the data is valid. we will get started with forms. so to add them to a page. for example. number.

I think. Again. when the entered data is invalid. Run it and see. the way that this is handled. and the input can validate automatically if the entered data is indeed a valid email address. depending on the used browser. not a valid email address that the browser will indicate this. we can see an input type date inside our form. Add the following codes in bold between welcome text and the footer. Here on the site. Input type email allows us. Again. Another new input type is URL. 1. So that means that it looks different. Page 7 of 23 . again. For the creation of this page. Indeed. in other words. this new input type email is included in the HTML5 file framework. to create an input where the user can enter a string. When this is not the case. It's rendered by the browser natively. as we can see at the bottom of the screen. The new input type equals date brings out-of-the-box support for a date picker in HTML5. So. and it's therefore easier to use this one straight away. we'll use of course these new input types.Ch_3 data. The major problem with dates. the browser will indicate this. is of course that the dates can be entered in many formats. it can be used to validate and to enter data is indeed a valid URL. as developers. The name really gives away for what this new input can be used. often has a different input format as well. is dependent on the browser. this would normally require us to use JavaScript. and depending on the region of the user. However. <section class="furnituredetails"> <header class="blockheader"> <span>Checkout</span> </header> </section> <footer> 2.

Time to form the form. ● The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute).html <form id="mainForm" action="#" method="post"> <fieldset class="box"> <legend>Your details</legend> <div> </div> </fieldset> </form> ● The HTML <form> element defines a form that is used to collect user input. Now add the first input element code in the field set. ● The form-data can be sent as URL variables (with method="get") or as HTTP post transaction (with method="post"). ● The <legend> tag defines a caption for the <fieldset> element. The <fieldset> tag draws a box around the related elements. Add the following code to the checkout. 4. An HTML form contains form elements.Ch_3 3. <p> <label class="textlabel" for="firstNameInput">First Name</label> Page 8 of 23 . ● The <fieldset> tag is used to group related elements in a form.

<p> <label class="textlabel" for="lastNameInput">Last Name</label> <input id="lastNameInput" name="LastName" type="text" required="required" placeholder="Enter your last name" class="textinput" size="10" maxlength="50" /> </p> <p> <label class="textlabel" for="emailInput">Email</label> <input id="emailInput" name="Email" type="email" class="textinput" required="required" placeholder="Please enter your email address" /> </p> <p> <label class="textlabel" for="streetInput">Address</label> <input id="streetInput" name="Street" type="text" class="textinput" required="required" placeholder="Please enter your shipping address" /> </p> <p> <label class="textlabel" for="phoneInput">Phone number</label> <input id="phoneInput" name="PhoneNumber" type="text" class="textinput" Page 9 of 23 . The for attribute of the <label> tag should be equal to the id attribute of the related element to bind them together. Now it is time to duplicate inputs and changing the necessary parameter for the rest of the input elements. However. ● Read the attributes for the <input> tag.Ch_3 <input id="firstNameInput" name="FirstName" type="text" required="required" maxlength="30" autofocus="autofocus" placeholder="Enter your first name" class="textinput" /> </p> ● The <label> tag defines a label for an <input> element. because if the user clicks on the text within the <label> element. it toggles the control. it provides a usability improvement for mouse users. they are quite self explanatory. 5. ● The <input> tag specifies an input field where the user can enter data and they are used within a <form> element to declare input controls that allow users to input data. The <label> element does not render as anything special for the user.

Add the following for the next fieldset which specify the required delivery date." /> </p> 6.Ch_3 required="required" placeholder="Please enter your phone number" /> </p> <p> <label class="textlabel" for="remarkInput">Remarks</label> <input id="remarkInput" name="PhoneNumber" type="text" class="textinput" placeholder="Please enter any extra remarks you have here. <br /> <fieldset class="box"> Page 10 of 23 . 7. you should see the following. Run and test the code.

Ch_3 <legend>Your order</legend> <div> <p> <label class="textlabel" for="deliveryDateInput">Requested delivery date</label> <input id="deliveryDateInput" name="BirthDate" class="textinput" type="date" placeholder="Enter a date" /> </p> </div> </fieldset> 8. Lastly. Page 11 of 23 . Remember to keep all these within the <form> tag. let us add the shopping cart and a submit button. 9. <div id="shoppingcart"> <header class="blockheader"><span>Shopping cart</span></header> <ul></ul> <br> <input type="submit" class="submitbutton" value="Place order" /> </div> 10.Run and see the result as it is finished except for the styling of course. Run and see the result.

} . display: block.Now let’s do some styling on the input element to make it visually aligned. height: 22px. Page 12 of 23 . margin: 0px. padding: 2px 5px. width: 250px.css /*Checkout page*/ .textinput { width: 300px. font-size: 14px. Add the following to the Layout. float: left. border: 1px solid #888888.textlabel { text-align: left. } fieldset { padding: 0px.Ch_3 11.

Run and see the result as it is finished. Page 13 of 23 .submitbutton { } 12.Ch_3 border: none. } . } fieldset > div { border: 2px solid #888888.

there is validation! You see. Wah lah. this is one of the feature of HTML5 that we discussed earlier. Page 14 of 23 .Now try pressingthe Place Order button without keying in anything.Now try keying in the date by pressing on the down arrow button.Ch_3 13. 14. There is automatically a calendar pop.

Remember in the product details page. Try it yourself.submitbutton { } We left out the search box! If you revisit the mockup or the end product. there is 3 thumbnails below the figure such that when we click on one of them. The search box is an input box with a placeholder. you might have realised that we have a search box on the top right corner of every page.Ch_3 Styling the Place order button You might have realised that I have purposely leave out the . JavaScript Time It is JavaSCript time for some interactivity in our web pages. . To start off. Now spend some time yourself in styling this button. Style the box such that it float to the right and change any CSS attribute that you deem fits. we will tread on something light. Page 15 of 23 .submitbutton class out of the styling. the figure displays the bigger version of the thumbnail.

4. this is just a testing code to make sure the linking between the pages work. Create a new folder called scripts in the root folder 2. Create a new file called productdetails. Type in the following.js and open it up in Visual Studio Code 3.js"></script> </head> 5.css" type="text/css" /> <script src="scripts/productdetails. Next is to link the two pages together. Test run the page and you should get an alert dialog box as shown below Page 16 of 23 . Add the following code to the header section in the productdetail.Ch_3 Preparing for the script 1. alert("It works").html <head> <meta charset="utf-8" /> <title>Welcome to Wood Premium Furniture Store!</title> <link rel="stylesheet" href="Styles/Layout.

What we are going to do is to work on the collection. . parameter2.)The code to be executed. by the function.src. Page 17 of 23 .. The Shopping Cart Next we are going into something slightly advanced. and dollar signs (same rules as variables). ● Next we replace the image source in the big figure with the one that is passed in.getElementById("expandedImg"). underscores. ● Note that the imgs is passed into the function during the function call opemImage(this). // Show the container element (hidden with CSS) expandImg.parentElement.html page on the add to cart and the shopping cart. 8. ● The getElementById() method returns the element that has the ID attribute with the specified value. followed by a name. Run the program and you should have your working mini image gallery. // Use the same src in the expanded image as the image being clicked on from the grid expandImg. is placed inside curly brackets: {} ● JavaScript variables are containers for storing data values and in this case var expandImg. followed by parentheses (). Once it is working.. function openImg(imgs) { // Get the expanded image var expandImg = document.display = "block". digits. this function will replace the current image in the figure with the one that if clicked. Before we start. Note that this is done programmatically not using CSS. ● Lastly. we change the CSS style of the figure to block. This refers to the small image that is clicked. So in our case here it return the img element which is the big figure. } ● A JavaScript function is a block of code designed to perform a particular task and is executed when it is invoked. 7. I just like to let you know that each Add to Cart button is padded with many information such as item and price that we will be using.style.Ch_3 6. let’s replace it with a function called openImage() . ● The function names can contain letters. The parentheses may include parameter names separated by commas: (parameter1.src = imgs. ● A JavaScript function is defined with the function keyword.

function (ev) { var furnitureId = this.getElementsByClassName("addtocartbutton").Next add the following code to the cart.getElementById("emptyCart"). var emptyCart = document.getAttribute("data-item").Ch_3 <div class="button . i < addtocartbtns. function (ev) { alert('hi'). This is important because we need all the html elements to be loaded in before we assigning event handler to them as you will see in the following explanation ● The statement: var addtocartbtns = document. for (var i = 0. alert(furnitureId + ' ' + furniturePrice). var emptyCart = document.getElementById("emptyCart"). 11. Page 18 of 23 . var cartitem = document. i++) { addtocartbtns[i]. var cartitem = document.querySelectorAll("#shoppingcart ul")[0]. window. All the elements found is put into an array. var shoppingcart = document.addEventListener("click".js.length.getElementsByClassName("addtocartbutton").querySelectorAll("#shoppingcart ul")[0]. 10. ● Finally the for loop statement loop through the array of buttons and add the click event handler so that it calls the function that contains the alert(‘hi’). searchs through the entire current document for all elements associated with the class addtocartbutton.onload is an event handler. i < addtocartbtns. ● The next few statement: var shoppingcart = document.getAttribute("data-price").00"> Add to Cart </div> 9. Let’s create a new JavaScript file called cart. It is triggered when the page is completely loaded. }). } } ● The window.length.getElementById("shoppingcart").js and associate it.getElementById("shoppingcart").onload = function() { var addtocartbtns = document. addtocartbutton" data-price="320.Modify the above statement alert statement to: for (var i = 0.addEventListener("click". The first statement gets the element with the id “shoppingcart” so that we can The second statement get the first item in the shopping cart and the last statement is for the button that has id “emptyCart”. i++) { addtocartbtns[i]. var furniturePrice = this.

i < addtocartbtns.js accordingly. i < currentCart.innerHTML = "". } }.id + " " + currentCart[i].Now that we have the information that we want we can add this as an object and store it in an array. UpdateShoppingCartUI(). var furniturePrice = this. for (var i = 0. Each item has 2 attributes. Add the following code just after the for loop. //alert(furnitureId + ' ' + furniturePrice). but make sure it is still within the window. }).appendChild(liElement).addEventListener("click". } ● The getAttribute is the one that retrieve the item info and the item embedded earlier in the addToCart button. var currentCart = new Array(). we will create the UpdateShoppingCartUI() function to update the display.Now. 13. ● Here we join them together to show the results. Modify the code in the cart.length. cartitem.getAttribute("data-item"). ● Finally we call the UpdateShoppingCartUI() function that we will be creating in a short while to update the display ● We comment the alert. } ● First.push(item).getAttribute("data-price"). 12.createElement('li'). liElement. function (ev) { var furnitureId = this. for (var i = 0. ● Once it is done.price + "".onload function function UpdateShoppingCartUI() { cartitem.Ch_3 }). i++) { var liElement = document. price:furniturePrice}. we add it to the array by pushing it. var item = {id:furnitureId.length. i++) { addtocartbtns[i]. we create a variable called currentCart to store an Array of furniture items.innerHTML = currentCart[i]. 1 is id which is the name of the furniture and the other is price. currentCart. Page 19 of 23 .

we will need to store all the item into a temporary storage space provide by the browser. function (ev) { currentCart = new Array().Run and test the collection. To solve this. 17. The JavaScript initialise itself everytime the page reloads. 16.It seems like we are done with shopping cart.html page to make sure it work on that page.Run and test the collection. UpdateShoppingCartUI(). 14. emptyCart. 15.Let’s do the empty cart button. After which.html page to make sure it work on that page. It is simple. but wait. Add the following code after the UpdateShoppingCartUI() function.Ch_3 ● The function first clear whatever that is in the list and then simply go through each item in the currentCart array and create a list item <li> for each of them. }). Add the following line in bold to the UpdateShoppingCartUI() function.addEventListener("click". Page 20 of 23 . it is added to the unordered list. just clear the array and update the UI. try navigating to another page and come back to the collection page and see what happen? All the items in the cart are gone.

Page 21 of 23 .stringify(currentCart)).price + "".length. the key cart will appear.innerHTML = currentCart[i].setItem('cart'. }.id + " " + currentCart[i].createElement('li'). 19. Click on the Application tab and select file:// under Local Storage.Ch_3 function UpdateShoppingCartUI() { cartitem. If you have click the addToCart button. i < currentCart. In Chrome.appendChild(liElement). ● What actually happen is that the information is stored in a storage called cart in the browser local storage. liElement. ● It will remain there until it is deleted. cartitem. hold down Ctrl .innerHTML = "". 18. for (var i = 0.Run the web page.Try adding and deleting the cart item to see the changes reflected in the localStorage as shown below.Shift . This will launch the developer tools in Chrome as shown below.J. JSON. i++) { var liElement = document. } localStorage.

So now what we need to do is to load the information from the localStorage everytime the page is refreshed.. if (!currentCart) { currentCart = new Array().length. } UpdateShoppingCartUI(). the cart in the localStorage still stores the information.Now try navigating away from the page.Try to navigate around and the cart information will be stored. currentCart = JSON.. Page 22 of 23 .getElementById("emptyCart"). After which we just need to call the UpdateShoppingCartUI() function to refresh the display. Modify the following code in bold near the beginning of the JavaScript page. You can even close the browser and re-open and the cart information will still stay. var emptyCart = document. i < addtocartbtns. The above code will work as long as either the addToCart button and the shopping cart unordered list. . ● What we are doing is simply getting the value from the localStorage and populate it to the currentCart...getItem('cart')). 21. i++) { .Ch_3 20. for (var i = 0.parse(localStorage. although the cart is emptied.

Conclusion We've reached the end of this third session. We started of with simple Javascript on the mini image gallery and move on to a more complicated shopping cart example. and we've also covered the automatic validation options. In this session we have done looking at all the new options we've received in HTML5 for entering data. checkout page and index page to see if the code works If any of it does not work that is because the addToCart button does not content the right class and right info Try to modify them to make sure that they work.End --- Page 23 of 23 . We have seen the numerous new input types which we have now in HTML5. --. So that's it for Session 3.Ch_3 Try attaching this code to product detail page.