LAB 15: Loops, Forms and API in JS - GCET



Lab-14Module:Web ProgrammingLevel:UG2Programme:Software EngineeringTime:1.30 hourStudent Name_________________________________ID_______________Date: 15 November 2017 Topic: Loops, Forms and API in JSLAB 15: Loops, Forms and API in JSTheoretical backgroundThe 'for' loop is the most compact form of looping. It includes the following three important parts ?The?loop initialization?where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.The?test statement?which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.The?iteration statement?where you can increase or decrease your counter.You can put all the three parts in a single line separated by semicolons.Practical Part Loops can execute a block of code a number of times.JavaScript LoopsLoops are handy, if you want to run the same code over and over again, each time with a different value.Often this is the case when working with arrays:Instead of writing:text += cars[0] +?"<br>";?text += cars[1] +?"<br>";?text += cars[2] +?"<br>";?text += cars[3] +?"<br>";?text += cars[4] +?"<br>";?text += cars[5] +?"<br>";You can write:HTML FILE<!DOCTYPE html><html><body><h2>JavaScript Loops</h2><p id="demo"></p><script>var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];var text = "";var i;for (i = 0; i < cars.length; i++) { text += cars[i] + "<br>";}document.getElementById("demo").innerHTML = text;</script></body></html>Different Kinds of LoopsJavaScript supports different kinds of loops:for?- loops through a block of code a number of timesfor/in?- loops through the properties of an objectwhile?- loops through a block of code while a specified condition is truedo/while?- also loops through a block of code while a specified condition is trueThe For LoopThe for loop is often the tool you will use when you want to create a loop.The for loop has the following syntax:for (statement 1;?statement 2;?statement 3) {????code block to be executed}Statement 1?is executed before the loop (the code block) starts.Statement 2?defines the condition for running the loop (the code block).Statement 3?is executed each time after the loop (the code block) has been executed.ExampleHTML FILE<!DOCTYPE html><html><body><h2>JavaScript Loops</h2><p id="demo"></p><script>var text = "";var i;for (i = 0; i < 5; i++) { text += "The number is " + i + "<br>";}document.getElementById("demo").innerHTML = text;</script></body></html>From the example above, you can read:Statement 1 sets a variable before the loop starts (var i = 0).Statement 2 defines the condition for the loop to run (i must be less than 5).Statement 3 increases a value (i++) each time the code block in the loop has been executed.The While LoopThe while loop loops through a block of code as long as a specified condition is true.Syntaxwhile (condition) {??? code block to be executed}ExampleIn the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10:HTML FILE<!DOCTYPE html><html><body><h2>JavaScript while</h2><p id="demo"></p><script>var text = "";var i = 0;while (i < 10) { text += "<br>The number is " + i; i++;}document.getElementById("demo").innerHTML = text;</script></body></html>Note: If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.The Do/While LoopThe do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.Syntaxdo {??? code block to be executed}while (condition);ExampleThe example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:HTML FILE<!DOCTYPE html><html><body><h2>JavaScript do ... while</h2><p id="demo"></p><script>var text = ""var i = 0;do { text += "<br>The number is " + i; i++;}while (i < 10); document.getElementById("demo").innerHTML = text;</script></body></html>Do not forget to increase the variable used in the condition, otherwise the loop will never end!JavaScript?FormsJavaScript Form ValidationHTML form validation can be done by JavaScript.If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form from being submitted:JavaScript ExampleThe function can be called when the form is submitted:HTML FILE<!DOCTYPE html><html><head><script>function validateForm() { var x = document.forms["myForm"]["fname"].value; if (x == "") { alert("Name must be filled out"); return false; }}</script></head><body><form name="myForm" action="/action_page_post.php"onsubmit="return validateForm()" method="post">Name: <input type="text" name="fname"><input type="submit" value="Submit"></form></body></html>JavaScript Can Validate Numeric InputJavaScript is often used to validate numeric input:HTML FILE<!DOCTYPE html><html><body><h2>JavaScript Can Validate Input</h2><p>Please input a number between 1 and 10:</p><input id="numb"><button type="button" onclick="myFunction()">Submit</button><p id="demo"></p><script>function myFunction() { var x, text; // Get the value of the input field with id="numb" x = document.getElementById("numb").value; // If x is Not a Number or less than one or greater than 10 if (isNaN(x) || x < 1 || x > 10) { text = "Input not valid"; } else { text = "Input OK"; } document.getElementById("demo").innerHTML = text;}</script></body></html>Automatic HTML Form ValidationHTML form validation can be performed automatically by the browser:If a form field (fname) is empty, the?required?attribute prevents this form from being submitted:HTML Form ExampleHTML FILE<!DOCTYPE html><html><body><form action="/action_page_post.php" method="post"> <input type="text" name="fname" required> <input type="submit" value="Submit"></form><p>If you click submit, without filling out the text field,your browser will display an error message.</p></body></html>Data ValidationData validation is the process of ensuring that user input is clean, correct, and useful.Typical validation tasks are:Has the user filled in all required fields?Has the user entered a valid date?Has the user entered text in a numeric field?Most often, the purpose of data validation is to ensure correct user input.Validation can be defined by many different methods, and deployed in many different ways.Server side validation?is performed by a web server, after input has been sent to the server.Client side validation?is performed by a web browser, before input is sent to a web server.HTML Constraint ValidationHTML5 introduced a new HTML validation concept called?constraint validation.HTML constraint validation is based on:Constraint validation?HTML?Input AttributesConstraint validation?CSS Pseudo SelectorsConstraint validation?DOM Properties and MethodsJavaScript?Validation APIIf an input field contains invalid data, display a message:The checkValidity() MethodHTML FILE<!DOCTYPE html><html><body><p>Enter a number and click OK:</p><input id="id1" type="number" min="100" max="300" required><button onclick="myFunction()">OK</button><p>If the number is less than 100 or greater than 300, an error message will be displayed.</p><p id="demo"></p><script>function myFunction() { var inpObj = document.getElementById("id1"); if (inpObj.checkValidity() == false) { document.getElementById("demo").innerHTML = inpObj.validationMessage; } else { document.getElementById("demo").innerHTML = "Input OK"; } } </script></body></html>ExamplesIf the number in an input field is greater than 100 (the input's max attribute), display a message:HTML FILE<!DOCTYPE html><html><body><p>Enter a number and click OK:</p><input id="id1" type="number" max="100"><button onclick="myFunction()">OK</button><p>If the number is greater than 100 (the input's max attribute), an error message will be displayed.</p><p id="demo"></p><script>function myFunction() { var txt = ""; if (document.getElementById("id1").validity.rangeOverflow) { txt = "Value too large"; } else { txt = "Input OK"; } document.getElementById("demo").innerHTML = txt;}</script></body></html>If the number in an input field is less than 100 (the input's min attribute), display a message:HTML FILE<!DOCTYPE html><html><body><p>Enter a number and click OK:</p><input id="id1" type="number" min="100"><button onclick="myFunction()">OK</button><p>If the number is less than 100 (the input's min attribute), an error message will be displayed.</p><p id="demo"></p><script>function myFunction() { var txt = ""; if (document.getElementById("id1").validity.rangeUnderflow) { txt = "Value too small"; } else { txt = "Input OK"; } document.getElementById("demo").innerHTML = txt;}</script></body></html> ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download