<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>form calculator</title> <script src="MyScript.js"></script> </head> <body> <h1>Products ordering form</h1> <p>Simply enter the number of products and item price to find out the total price of your order</p> <form onsubmit="return calcTotal()" action="#" method="post" id="calcForm"> <p> <label for="quantity">Enter number of products wanted:</label> <input name="quantity" id="quantity" /> </p> <p> <label for="price">Enter price of product wanted:</label> <input name="price" id="price" /> </p> <p> <input value="Total price" type="submit"> <!--Just to send another page --> </p> </form> <div id="message"></div> </body> </html> function calcTotal() { //get inputs - qty and item price var qty = document.getElementById("quantity").value; var price = document.getElementById("price").value; //validation - missing inputs, non-digit inputs, negative numbers if (qty == "" || price == "") { document.getElementById("message").innerHTML = "Missing inputs"; } else if (isNaN(qty) || isNaN(price)) { document.getElementById("message").innerHTML = "Digits only"; } else if (qty < 0 || price < 0) { document.getElementById("message").innerHTML = "Positive numbers only"; } else { //calc - find the total price = qty * item price var totalPrice = qty * price; // display the output total price document.getElementById("message").innerHTML = "Total price is " + totalPrice; } return false; //prevent form submission //calc - find the total price = qty * item price var totalPrice = qty * price; // display the output total price document.getElementById("message").innerHTML = "Total price is " + totalPrice; return false; //prevent from submission }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter