Get javascript values from calculation and insert them into mysql database - javascript

i want to make calories calculator.the code below shows the result. and it is good. but i want the result in input field, so that i can submit the result of the calculation into mysql database. this calculation was automatically calculate. i want the calculation was not auto calculate and the result was in input field.
<?php
session_start();**strong text**
include 'dbconnection.php';
if(isset($_POST['submit'])){
$jantina = $_POST['jantina'];
$umur = $_POST['umur'];
$berat = $_POST['berat'];
$tinggi = $_POST['tinggi'];
$totalCals = $_POST['totalCals'];
//yg bmr ni , nilai yang dah dikira auto
$query = "INSERT INTO kalori (jantina, umur, berat, tinggi, totalCals)";
$query .= "VALUES ('$jantina', '$umur', '$berat', '$tinggi', '$totalCals')";
$create_post_query = mysqli_query($connection, $query);
echo"<script language=javascript type=text/javascript> alert ('Anda berjaya
daftar.')
</script>";
}
?>
<form class="form" method="post" action="kalori1.php" autocomplete="off">
<div class="form-group">
<label for="gender">Jantina</label>
<div class="input-group" data-toggle="buttons" >
<label class="btn btn-default active"><input id="female" type="radio" name="jantina" onchange="calsPerDay()" checked="checked">Perempuan</label>
<label class="btn btn-default"><input id="male" type="radio" name="jantina" onchange="calsPerDay()" >Lelaki</label>
</div>
</div>
<div class="form-group">
<label for="age">Umur</label>
<div class="input-group" data-validate="number">
<input id="age" type="number" oninput="calsPerDay()" placeholder="tahun" name="umur" required>
</div>
</ <div class="form-group">
<label>Berat</label>
<div class="input-group" data-validate="number">
<input id="weight" type="number" oninput="calsPerDay()" placeholder="in kg" name="berat" required>
</div>
</div>
<div class="form-group">
<label>Tinggi</label>
<div class="input-group" data-validate="number">
<input id="height" type="number" oninput="calsPerDay()" placeholder="in cm" name="tinggi" required>
</div>
</div>
<br>**strong text**
<label><span id="totalCals" ></span></label><br>
<input id="totalcals">
<br>
<input name="submit" type="submit" id="submit" value="Submit" >
</form>
function calsPerDay() {
function find(id) { return document.getElementById(id) }
var age = find("age").value
var height = find("height").value
var weight = find("weight").value
var result = 0
if (find("male").checked)
result = 66.47 + (13.75 * weight) + (5.0 * height - (6.75 * age))
else if (find("female").checked)
result = 665.09 + (9.56 * weight) + (1.84 * height - (4.67 * age))
find("totalCals").innerHTML = Math.round( result )
}
calsPerDay()

Related

how can we display html form values as many times as the user insert them by pressing submit button each time?

<form action="#"></form>
<label for="First-name">First name: </label>
<input type="text" id="First-name" placeholder="Please insert fiid."><br>
<label for="Second-name">Second name: </label>
<input type="text" id="Second-name" placeholder="Please insert second name"> <br>
<label for="Passenger-weight">Passengers weight: </label>
<input type="number" class="weight" id ="Passenger-weight" placeholder="Please enter passengers weight"><br>
<label for="cargo-weight">cargo weight: </label>
<input type="number" class="weight" id ="cargo-weight" placeholder="Please enter cargo weight"><br>
<input type="submit" id ="submit" ><br>
</form>
<p id="sum"></p>
<div id="sumoftotal"></div>
<body>
<script language="JavaScript">
document.getElementById("submit").onclick=function (){
let firstName = document.getElementById("First-name").value;
let lastName= document.getElementById("Second-name").value;
let num1 = document.getElementById("Passenger-weight").value;
let num2 = document.getElementById("cargo-weight").value;
let total =parseInt(num1) + parseInt(num2);
document.getElementById("sum").innerHTML=(`${firstName} ${lastName} ${total }`)
}
</script>
</body>
my problem can be numbered:
number 1: when I press the submit button, input values show up, BUT when I want to insert a different data, the previous one disappear. I studied about it, because whatever comes in the function scope become local we cannot apply it outside, BUT I don't know how to change it.
number 2: I want to have the sum of total weights I insert at the end of my list, I know we can do this by loop, BUT I need something simpler and more preliminary because I am a novice and it would be a big jump for the time being.
all in all, I would be happy if anyone could help me.
Here is the primary and most basic approach.
var data = document.getElementById('data');
var weightElement = document.getElementById('total-weight');
document.getElementById("submit").onclick = function() {
/* Getting data */
let firstName = document.getElementById("First-name").value;
let lastName = document.getElementById("Second-name").value;
let num1 = document.getElementById("Passenger-weight").value;
let num2 = document.getElementById("cargo-weight").value;
let total = parseInt(num1) + parseInt(num2);
/* Appending element */
data.innerHTML = data.innerHTML + `First Name - ${firstName}, Last Name - ${lastName}, Weight - ${total} <br/>`;
weightElement.innerHTML = parseInt(weightElement.innerHTML) + total;
}
<body>
<form action="#"></form>
<label for="First-name">First name: </label>
<input type="text" id="First-name" placeholder="Please insert fiid."><br>
<label for="Second-name">Second name: </label>
<input type="text" id="Second-name" placeholder="Please insert second name"> <br>
<label for="Passenger-weight">Passengers weight: </label>
<input type="number" class="weight" id="Passenger-weight" placeholder="Please enter passengers weight"><br>
<label for="cargo-weight">cargo weight: </label>
<input type="number" class="weight" id="cargo-weight" placeholder="Please enter cargo weight"><br>
<input type="submit" id="submit"><br>
</form>
<div id="data"></div>
<div>Total weight = <span id="total-weight">0</span></div>
</body>

Radio button validation javascript

I created a calculator in HTML/js, now am trying to add some validation to it but I can't seem to get it to work.
In the below calculator, I added a script that checked if the sex radio button has not been checked then output a message. Unfortunately, when I ran it the message isn't showing anything. Help please
function calcCreatine() {
var sexInput = document.querySelector('input[name="sex"]:checked').value;;
var ageInput = document.getElementsByName("patients-age")[0].value;
var weightInput = document.getElementsByName("patients-weight")[0].value;
var serumInput = document.getElementsByName("patients-serum")[0].value;
var result;
if (sexInput == null) {
return document.getElementById("outs").innerHTML = "Please enter a value";
} else {
if (sexInput === 'm') {
result = Math.round(((140 - ageInput) * weightInput * 1.23) / serumInput);
result = result.toString().bold().fontsize(6);
resultText = " mL/min".small() + " - Creatinine clearance.";
res = result + resultText.bold();
return document.getElementById("outs").innerHTML = res;
} else {
result = Math.round(((140 - ageInput) * weightInput * 1.04) / serumInput);
result = result.toString().bold().fontsize(6);
resultText = " mL/min".small() + " - Creatinine clearance.";
res = result + resultText.bold();
return document.getElementById("outs").innerHTML = res;
}
}
}
<!-- Creatinine clearance calculator. -->
<form id="form-id" method="post">
<div id="creat-calc">
<div class="card">
<div class="card-header py-3">
<h5 class="m-0 font-weight-bold text-primary"><strong>Creatinine clearance
calculator</strong></h5>
</div>
<div class="card-body">
<p>Sex of patient:</p>
<div>
<label class="radio-inline">
<input type="radio" name="sex" value="m"> Male
</label>
<label class="radio-inline">
<input type="radio" name="sex" value="f"> Female
</label>
<p>Age of patient (years):</p>
<input type="number" min="1" max="120" name="patients-age" />
<br/><br/>
<p>Weight of patient (kg):</p>
<input type="number" min="1" max="120" name="patients-weight" />
<br/><br/>
<p>Serum creatinine (micromol/L):</p>
<input type="number" min="1" max="120" name="patients-serum" />
<br/>
</div>
<br/>
<hr/>
<div id="crtresult">
<h5 id="outs"></h5>
<p>Original Cockcroft-Gault Equation: <u> mdcalc website</u></p>
</div>
<button type="button" class="btn btn-primary" onclick="calcCreatine();">Calculate
</button>
<button type="button" class="btn btn-danger" onclick="popup.hideCeatCalcFormPopup();">
Close
</button>
<button type="reset" class="btn btn-primary" onclick="resetButton();">Reset</button>
</div>
</div>
</div>
</form>
The problem here is that when you are not selecting any radio button, following statements returns null:
document.querySelector('input[name="sex"]:checked')
since its null this cannot have value property. So I did some modification in the code and stored the whole input instead of the value and then used it later with value property wherever needed.
Here's the solution. Try it yourself:
function calcCreatine() {
var sexInput = document.querySelector('input[name="sex"]:checked');
var ageInput = document.getElementsByName("patients-age")[0];
var weightInput = document.getElementsByName("patients-weight")[0];
var serumInput = document.getElementsByName("patients-serum")[0];
var result;
if (sexInput == null) {
return document.getElementById("outs").innerHTML = "Please select your gender";
} else {
if (sexInput.value === 'm') {
result = Math.round(((140 - ageInput.value) * weightInput.value * 1.23) / serumInput.value);
result = result.toString().bold().fontsize(6);
resultText = " mL/min".small() + " - Creatinine clearance.";
res = result + resultText.bold();
return document.getElementById("outs").innerHTML = res;
} else {
result = Math.round(((140 - ageInput.value) * weightInput.value * 1.04) / serumInput.value);
result = result.toString().bold().fontsize(6);
resultText = " mL/min".small() + " - Creatinine clearance.";
res = result + resultText.bold();
return document.getElementById("outs").innerHTML = res;
}
}
}
<!-- Creatinine clearance calculator. -->
<form id="form-id" method="post">
<div id="creat-calc">
<div class="card">
<div class="card-header py-3">
<h5 class="m-0 font-weight-bold text-primary"><strong>Creatinine clearance
calculator</strong></h5>
</div>
<div class="card-body">
<p>Sex of patient:</p>
<div>
<label class="radio-inline">
<input type="radio" name="sex" value="m"> Male
</label>
<label class="radio-inline">
<input type="radio" name="sex" value="f"> Female
</label>
<p>Age of patient (years):</p>
<input type="number" min="1" max="120" name="patients-age" />
<br/><br/>
<p>Weight of patient (kg):</p>
<input type="number" min="1" max="120" name="patients-weight" />
<br/><br/>
<p>Serum creatinine (micromol/L):</p>
<input type="number" min="1" max="120" name="patients-serum" />
<br/>
</div>
<br/>
<hr/>
<div id="crtresult">
<h5 id="outs"></h5>
<p>Original Cockcroft-Gault Equation: <u> mdcalc website</u></p>
</div>
<button type="button" class="btn btn-primary" onclick="calcCreatine();">Calculate
</button>
<button type="button" class="btn btn-danger" onclick="popup.hideCeatCalcFormPopup();">
Close
</button>
<button type="reset" class="btn btn-primary" onclick="resetButton();">Reset</button>
</div>
</div>
</div>
</form>
There are a couple of issues with your code.
var sexInput = document.querySelector('input[name="sex"]:checked').value;
This line is trying to get the value of the selected sex. If the form has just loaded and the user has not selected anything yet, then:
document.querySelector('input[name="sex"]:checked');
Will be null, so you will get an error:
Uncaught TypeError: Cannot read property 'value' of null
The simplest way to fix that would be to just add a default value to the radio buttons, for example:
<input type="radio" name="sex" value="m" checked>
That being said, you can also improve the following:
The <font> tag has been removed from HTML5, so it would be a good idea to replace that.
Since patient sex only affects one line of your code, you can remove the duplicate part by just calculating the result in an if statement and doing the rest only once.
I have created this fiddle to demonstrate.
The first problem is the code is the double ";" in the first line please, change it:
var sexInput = document.querySelector('input[name="sex"]:checked').value;;
to:
var sexInput = document.querySelector('input[name="sex"]:checked').value;
The second problem in you radio button is not working because you are trying to get a value from an element that doesn't exist if you don't check the button but if you check it and you execute the calculate button then you get an error:
and this error is because you are trying to obtain a value from an element that doesn't exist yet.
How to solve it?
You can modify the first line to get the null value from the element like this:
var sexInput = document.querySelector('input[name="sex"]:checked');
then if the user not check the radio button you will get a null value.
Another way could be using the checked property of the element to evaluate if the user checked the button using true/false like this:
var sexInput = document.querySelector('input[name="sex"]').checked;
then in your code you can eval like this:
if(sexInput){
// Do something
}
EDIT
I added a working exmaple:
EDIT 2
Improved the response a little bit more.
function calcCreatine() {
var sexInput = document.querySelector('input[name="sex"]:checked');
var ageInput = document.getElementsByName("patients-age")[0].value;
var weightInput = document.getElementsByName("patients-weight")[0].value;
var serumInput = document.getElementsByName("patients-serum")[0].value;
var result;
if (sexInput == null) {
return document.getElementById("outs").innerHTML = "Please enter a value";
} else {
if (sexInput === 'm') {
result = Math.round(((140 - ageInput) * weightInput * 1.23) / serumInput);
result = result.toString().bold().fontsize(6);
resultText = " mL/min".small() + " - Creatinine clearance.";
res = result + resultText.bold();
return document.getElementById("outs").innerHTML = res;
} else {
result = Math.round(((140 - ageInput) * weightInput * 1.04) / serumInput);
result = result.toString().bold().fontsize(6);
resultText = " mL/min".small() + " - Creatinine clearance.";
res = result + resultText.bold();
return document.getElementById("outs").innerHTML = res;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="asd.js"></script>
</head>
<body>
<!-- Creatinine clearance calculator. -->
<form id="form-id" method="post">
<div id="creat-calc">
<div class="card">
<div class="card-header py-3">
<h5 class="m-0 font-weight-bold text-primary">
<strong>Creatinine clearance calculator</strong>
</h5>
</div>
<div class="card-body">
<p>Sex of patient:</p>
<div>
<label class="radio-inline">
<input type="radio" name="sex" value="m" /> Male
</label>
<label class="radio-inline">
<input type="radio" name="sex" value="f" /> Female
</label>
<p>Age of patient (years):</p>
<input type="number" min="1" max="120" name="patients-age" />
<br /><br />
<p>Weight of patient (kg):</p>
<input type="number" min="1" max="120" name="patients-weight" />
<br /><br />
<p>Serum creatinine (micromol/L):</p>
<input type="number" min="1" max="120" name="patients-serum" />
<br />
</div>
<br />
<hr />
<div id="crtresult">
<h5 id="outs"></h5>
<p>
Original Cockcroft-Gault Equation:
<a
href="https://www.mdcalc.com/creatinine-clearance-cockcroft-gault-equation#creator-insights"
style="color: white"
><u> mdcalc website</u></a
>
</p>
</div>
<button
type="button"
class="btn btn-primary"
onclick="calcCreatine();"
>
Calculate
</button>
<button
type="button"
class="btn btn-danger"
onclick="popup.hideCeatCalcFormPopup();"
>
Close
</button>
<button
type="reset"
class="btn btn-primary"
onclick="resetButton();"
>
Reset
</button>
</div>
</div>
</div>
</form>
</body>
</html>
Regards

Javascript percentage calculation for each form field

I'm trying to work out the percentage value for each field in a form. However my current code is only working out the value for the first field or whichever one is focused.
I'd like it so that the percentage value only for the filed in the same fieldset
The current code works but i'd like to apply to to multiple fieldsets without them interfering with other inputs on the same page
In the snippet you can see that the two separate amounts which are editing each others details
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$($percentage).add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var percentage = parseFloat($(this).val());
var price = parseFloat($price.val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$increase.text(newPrice);
$increaseWrap.fadeIn();
if (isNaN(newPrice)) {
$increaseWrap.hide();
}
}
function calculatePerc() {
var percentage = $percentage.val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$increase.text(newPrice);
}
function removePercent() {
$increaseWrap.fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 1</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[0]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 2</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[1]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="13005.02" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage2">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage2">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
Instead of IDs, use classes and DOM traversal functions to find the fields in the same fieldset.
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$percentage.add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var $fieldset = $(this).closest("fieldset");
var percentage = parseFloat($(this).val());
var price = parseFloat($fieldset.find(".form-item--invamt .form-item__input").val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
$fieldset.find(".wrapper-types__percentage").fadeIn();
if (isNaN(newPrice)) {
$fieldset.find(".wrapper-types__percentage").hide();
}
}
function calculatePerc() {
var $fieldset = $(this).closest("fieldset");
var percentage = $fieldset.find(".form-item__input-expand .percentage").val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
}
function removePercent() {
var $fieldset = $(this).closest("fieldset");
$fieldset.find(".wrapper-types__percentage").fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>

How to validate total sum through jquery?

I have this field where the total amount is written and another field below the total amount field which can be appended multiple times by jQuery and the total amount written in field below can't exceed the amount in the total amount field. Is there any way to calculate this?
Form:
<div class="form-group">
<label>Total Cost</label>
<input type="number" name="total_cost" id="total_cost" class="form-control">
</div>
<div class="col-md-6">
<label>Amount</label>
<div class="input-group">
<input type="text" name="scheduled[1][amount]" class="form-control txt-schedule-amount" placeholder="Enter Amount">
</div>
</div>
As addition to Optimus answer you can add these lines:
$('body').on('keyup','.txt-schedule-amount',function(){
if(!calculateSum()) return false;
return true;
})
Which will check amounts during editing
I think you are looking for this.
function calcSum(obj){
var tAmmount =0;
$( ".txt-schedule-amount" ).each(function() {
tAmmount = tAmmount + valueParse($(this).val());
});
var costVal = valueParse($('#total_cost').val());
if(tAmmount > costVal){
alert('Your ammount exceed.');
if(obj==false)
$(".txt-schedule-amount").val(0);
else
$(obj).val(0);
}
}
function valueParse(svalue){
svalue = parseFloat(svalue);
if(isNaN(svalue))
svalue = 0;
return svalue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label>Total Cost</label>
<input type="number" name="total_cost" id="total_cost" class="form-control" onblur="calcSum(false)">
</div>
<div class="col-md-6">
<label>Amount</label>
<div class="input-group">
<input type="text" name="scheduled[1][amount][]" class="form-control txt-schedule-amount" onblur="calcSum(this)" placeholder="Enter Amount">
<input type="text" name="scheduled[1][amount][]" class="form-control txt-schedule-amount" onblur="calcSum(this)" placeholder="Enter Amount">
</div>
</div>
I think this is what you need.On submit call this function
function calculateSum(){
var sum =0;
$( ".txt-schedule-amount" ).each(function() {
sum = sum + parseInt($(this).val());
});
$("#total_cost").val(sum);
}

HTML Validation JS without using PHP

I made an application for people to fill out an application. I did some of the in form validation but now I want to ensure that when the user hits the submit button it checks to ensure that all field are filled out. I am stuck and cannot figure out the last part of this puzzle.
I believe all I need to make this work is a Application.js If someone could take a look at this and let me know what if anything I am missing. I did not include the CSS sheet or photos. Thank you for taking the time to help.
Here is the form. "Application.html"
<!DOCTYPE html>
<html>
<head>
<center><h1>AIFC Application Form</h1></center>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<title>AIFC Application</title>
<meta charset="utf-8">
<meta name="author" content="Paul Skinner">
<link rel="stylesheet" type="text/css" href="Application.css" />
<style type="text/css">
</style>
<script src="Application.js"></script>
<script src="Application_Library.js"></script>
<script type="text/javascript">
function updateTotal() {
var basePrice = 50;
var optionsPrice = 0;
var memberPrice = 0;
function checkPayment() {
if (document.getElementById('payment0').checked) {
optionsPrice += 1;
}
if (document.getElementById('payment1').checked) {
optionsPrice += 9.6;
}
} // end of checking for payment
function checkJumper() {
if (document.getElementById('jumper0').checked) {
optionsPrice += 0;
}
if (document.getElementById('jumper1').checked) {
optionsPrice += 4.4;
}
} // end of checking for Jumper
function checkMembership() {
if (document.getElementById('membership').value == 'Basic') {
memberPrice += 75;
}
if (document.getElementById('membership').value == 'Silver') {
memberPrice += 125;
}
if (document.getElementById('membership').value == 'Gold') {
memberPrice += 150;
}
} // end of check membership function
checkPayment();
checkJumper();
checkMembership();
var totalPrice = basePrice + (optionsPrice * memberPrice);
document.getElementById('optionsPrice').innerHTML = optionsPrice;
document.getElementById('memberPrice').innerHTML = "$ " + memberPrice;
document.getElementById('totalPrice').innerHTML = "$ " + totalPrice;
}
</script>
</head>
<body>
<div id="top">
<nav class="horizontalNav">
<ul>
<li>Home</li>
<li>Application</li>
<li>Who We Are</li>
<li>Our Packages</li>
</ul>
</nav></div>
<section>
<table>
<tr style="white-space:nowrap; clear:both">
<td><img src="Images/girl punching.jpg" alt="Girl Punching" style=" float:left; height:200px" /></td>
<td><img src="images/fitness.jpg" alt="Weights" style=" float:right; height:200px; width:900px" /></td>
</tr>
</table>
</section>
<form action="#" method="get" name="application" id="application" >
<div id="form">
<fieldset>
<legend>Payment Type</legend><br>
<input type="radio" name="payment" id="payment0" value="payment0" onchange="updateTotal()"> Monthly membership <br>
<input type="radio" name="payment" id="payment1" value="payment1" onchange="updateTotal()"> Yearly membership <b>Big Savings!</b> <br><br>
</fieldset>
<fieldset>
<legend>Choose a Location</legend><br>
<input type="radio" name="jumper" id="jumper0" value="jumper0" onchange="updateTotal()"> Single Gym location
<input type="radio" name="jumper" id="jumper1" value="jumper1" onchange="updateTotal()"> All Locations <br><br>
</fieldset>
<fieldset>
<legend>Membership Type</legend><br>
<select name="membership" id="membership" onchange="updateTotal()">
<option value="Basic">Basic Membership ($75)</option>
<option value="Silver">Silver Membership ($125)</option>
<option value="Gold">Gold Membership ($150)</option><br>
</select>
</fieldset>
<fieldset>
<legend>Sex</legend><br>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
</fieldset>
</div>
<div id="prices">
<table>
<tr><td>Membership Application Fee</td><td id="basePrice">$50</td></tr>
<tr><td>Option factor</td><td id="optionsPrice"></td></tr>
<tr><td>Membership</td><td id="memberPrice"></td></tr>
<tr><td>Total</td><td id="totalPrice"></td></tr>
</table>
</div>
<div id="info">
<fieldset>
<legend>Personal Information</legend>
<label for="first_name">First Name:</label>
<input type="text" id="firstname" name="first" required autofocus title="First Name" placeholder="First Name" />
<span id="first_name_error"> </span><br>
<label for="last_name">Last Name:</label>
<input type="text" id="lastname" name="last" required title="Last Name" placeholder="Last Name"/>
<span id="last_name_error"> </span><br>
<label for="address">Address:</label>
<input type="text" id="address" name="address" required title="Address" placeholder="Address"/>
<span id="address_error"> </span><br>
<label for="city">City:</label>
<input type="text" id="city" name="city" required title="City" placeholder="City"/>
<span id="city_error"> </span><br>
<label for="state">State:</label>
<input type="text" id="state" maxlength="2" name="State" required title="State" placeholder="State"/>
<span id="state_error"> </span><br>
<label for="zip_code">Zip Code:</label>
<input type="text" id="zip" name="zip" required title="Zip Code" placeholder="Zip Code" pattern="\d{5}([\-]\d{4})?"/>
<span id="zip_error"> </span><br>
<label for="phone_number">Phone Number:</label>
<input type="text" id="phone" name="phone" required title="Optional Phone Number 999-999-9999" placeholder="999-999-9999" pattern="\d{3}[\-]\d{3}[\-]\d{4}"/>
<span id="phone_error"> </span><br>
<label for="date_of_birth">Date of Birth:</label>
<input type="date" name="date" required title="MM-DD-YYYY"/>
<span id="date_error"> </span><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required title="Email" placeholder="Email Address"/>
<span id="email_error"> </span>
<br>
</fieldset>
<br><br><center><input type="submit" id="submit" value="Become a Member"></center>
<br><center><input type="Reset" id="btn1" value="Reset Form"></center>
</div>
<br><br><div class="footer">
<address><center>
<b>American InterContinental Fitness Center</b> ☀
1578 Perseverance Lane ☀
Simple City, IL 60001
<br/> (630)432-1425
</address></center>
<br>
</div>
</form>
</body>
</html>
The next is the js: "Application_Library.js"
var $ = function (id) { return document.getElementById(id); }
var application = function () {
// All the different fields
this.field = [];
this.field["first_name"] = {};
this.field["last_name"] = {};
this.field["address"] = {};
this.field["city"] = {};
this.field["state"] = {};
this.field["zip"] = {};
this.field["phone"] = {};
this.field["date"] = {};
this.field["email"] = {};
// Field messages
this.field["state"].message = "Please use only a two letter State abbreviation.";
this.field["zip"].message = "Please use a 5 or 9 digit Zip Code";
this.field["phone"].message = "Please use 123-456-7890 format.";
this.field["email"].message = "Must be a vaild email address.";
// Error messages
this.field["email"].required = "Email is required";
this.field["confirmemail"].required = "Please confirm your email!";
this.field["confirmemail"].noMatch = "Emails do not Match!", "email";
this.field["first_name"].required = "First names are required.";
this.field["last_name"].required = "Last names are required.";
this.field["address"].required = "An Address is required";
this.field["city"].required = "A City is required";
this.field["state"].required = "A State is required";
this.field["state"].isState = "State invalid";
this.field["zip"].required = "A Zip code is required.";
this.field["zip"].isZip = "Zip code is invalid";
this.field["phone"].required = "A phone number is required";
this.field["phone"].isPhone = "The phone number is invalid";
this.field["date"].required = "Your date of birth is required";
}
Instead of writing your own javascript validation you can use the jQuery "form Validation Plug-in", which is an excellent tool for web pages to validate data entries at the client side using JavaScript. It's very simple to use.
Here is a sample tutorial
http://www.codeproject.com/Articles/213138/An-Example-to-Use-jQuery-Validation-Plugin
You should implement server side validation also for best security.
You can't just check data on JavaScript, you should also check it on server-side, because the client side is more accessible and user can change the JavaScript or even disable it, so the data would be invalidated.
You should write server-side validation too.
You forgot to show the Application.js file.
Also you can use HTML5 validation, without using any JavaScript:
http://www.sitepoint.com/html5-form-validation/

Categories

Resources