Need help getting fields to Populate using Javascript - javascript

I am taking an introduction course to HTML and have been struggling to find my error with a page that uses java. I am sure I am making a simple mistake but I am not seeing it
Here is the fiddle of the code I am working with:
https://jsfiddle.net/Terranova1340/ctc66nmu/2/
<body onload="processForm()">
<div id="wrapper">
<form id="cars" method="get">
<h1>AutoMart Sales Order Form</h1>
<img id="imgCar" src="civic2.jpg" />
<table class="Controls">
<tr>
<td><label for="Model">Select a Model:</label><br></td>
<td><select id="selModel" onchange="chgImage()">
<option value="civic" >Civic</option>
<option value="accord" >Accord</option>
</select></td>
</tr>
<tr>
<td><label for="optAcces">Optional Accessories:</label><br></td>
<td><label class='checkbox'><input type="checkbox" id="optAcces1"value="stereoSys" onchange="processForm()"> Stereo System<br>
<label class='checkbox'><input type="checkbox" id="optAcces2" value="leatherInt" onchange="processForm()"> Leather Interiors<br>
<label class='checkbox'><input type="checkbox" id="optAcces3" value="gpsSys" onchange="processForm()"> GPS System<br><br>
</td>
</tr>
<tr>
</tr>
<tr>
<tr>
</tr>
<td><label for="extFin">Exterior Finish:</label><br></td>
<td><label class='radiolabel'><input type="radio" name="selectedfinish" id="stanFin" onchange="processForm()"> Standard Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="metalFin" onchange="processForm()"> Metalic Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="custFin" onchange="processForm()"> Customized Finish<br>
</td>
</tr>
<tr>
<td><label for="base">Base Price</label><br></td>
<td><input type="text" id="basePrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="access">Accessories Price</label><br></td>
<td><input type="text" id="accessPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="extPrice">Exterior Finish Price</label><br></td>
<td><input type="text" id="extPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label>Estimated Total Price</label><br></td>
<td><input class- "ReadOnlyControls" type="text" name="estPrice" id="estPrice" style="text-align:right;" readonly><br></td>
</tr>
</table>
<input class="buttons" type="reset" value="Clear">
<input class="buttons" type="button" onclick="window.print()"; value="Print Form" id="print">
</form>
</div>
</body>
</html>
Java is
function chgImage() {
if (document.getElementById("selModel").value =="civic")
{
document.getElementById("imgCar").src="Civic2.jpg";
}
else
{
document.getElementById("imgCar").src="Accord2.jpg";
}
processForm();
}
function processForm(){
var bPrice = 0;
var aPrice = 0;
var oPrice = 0;
var tPrice = 0;
if (document.getElementById("selModel").value =="civic")
{
bPrice = 17355.89;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 400.22;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 850.44;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 305.72;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 350.00;
}
}
else
{
basePrice = 19856.79;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 500.89;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 1015.85;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 385.67;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 400.00;
}
}
//calculate total
tPrice = bPrice+aPrice+oPrice;
document.getElementById("basePrice").value = "$" + formatCurrency(bPrice).toString();
document.getElementById("accessPrice").value = "$" + formatCurrency(aPrice).toString();
document.getElementById("extPrice").value = "$" + formatCurrency(oPrice).toString();
document.getElementById("estPrice").value = "$" + formatCurrency(tPrice).toString();
}
function formatCurrency(num){
num = isNaN(num) || num === ''|| num === null ? 0.00 : num;
return parseFloat(num).toFixed(2);
}
My issue is the Base Price to Estimated Total Price fields aren't populating.
Thanks in advance!

function chgImage() {
if (document.getElementById("selModel").value =="civic")
{
document.getElementById("imgCar").src="Civic2.jpg";
}
else
{
document.getElementById("imgCar").src="Accord2.jpg";
}
processForm();
}
function processForm(){
var bPrice = 0;
var aPrice = 0;
var oPrice = 0;
var tPrice = 0;
if (document.getElementById("selModel").value =="civic")
{
bPrice = 17355.89;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 400.22;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 850.44;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 305.72;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 350.00;
}
}
else
{
basePrice = 19856.79;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 500.89;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 1015.85;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 385.67;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 400.00;
}
}
//calculate total
tPrice = bPrice+aPrice+oPrice;
document.getElementById("basePrice").value = "$" + formatCurrency(bPrice).toString();
document.getElementById("accessPrice").value = "$" + formatCurrency(aPrice).toString();
document.getElementById("extPrice").value = "$" + formatCurrency(oPrice).toString();
document.getElementById("estPrice").value = "$" + formatCurrency(tPrice).toString();
}
function formatCurrency(num){
num = isNaN(num) || num === ''|| num === null ? 0.00 : num;
return parseFloat(num).toFixed(2);
}
<body onload="processForm()">
<div id="wrapper">
<form id="cars" method="get">
<h1>AutoMart Sales Order Form</h1>
<img id="imgCar" src="civic2.jpg" />
<table class="Controls">
<tr>
<td><label for="Model">Select a Model:</label><br></td>
<td><select id="selModel" onchange="chgImage()">
<option value="civic" >Civic</option>
<option value="accord" >Accord</option>
</select></td>
</tr>
<tr>
<td><label for="optAcces">Optional Accessories:</label><br></td>
<td><label class='checkbox'><input type="checkbox" id="optAccess1"value="stereoSys" onchange="processForm()"> Stereo System<br>
<label class='checkbox'><input type="checkbox" id="optAccess2" value="leatherInt" onchange="processForm()"> Leather Interiors<br>
<label class='checkbox'><input type="checkbox" id="optAccess3" value="gpsSys" onchange="processForm()"> GPS System<br><br>
</td>
</tr>
<tr>
</tr>
<tr>
<tr>
</tr>
<td><label for="extFin">Exterior Finish:</label><br></td>
<td><label class='radiolabel'><input type="radio" name="selectedfinish" id="stanFin" onchange="processForm()"> Standard Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="metalFin" onchange="processForm()"> Metalic Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="custFin" onchange="processForm()"> Customized Finish<br>
</td>
</tr>
<tr>
<td><label for="base">Base Price</label><br></td>
<td><input type="text" id="basePrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="access">Accessories Price</label><br></td>
<td><input type="text" id="accessPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="extPrice">Exterior Finish Price</label><br></td>
<td><input type="text" id="extPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label>Estimated Total Price</label><br></td>
<td><input class- "ReadOnlyControls" type="text" name="estPrice" id="estPrice" style="text-align:right;" readonly><br></td>
</tr>
</table>
<input class="buttons" type="reset" value="Clear">
<input class="buttons" type="button" onclick="window.print()"; value="Print Form" id="print">
</form>
</div>
</body>
</html>
You are using wrong id's, change to optAccess1,optAccess2,optAccess3 here
<td><label class='checkbox'><input type="checkbox" id="optAccess1"value="stereoSys" onchange="processForm()"> Stereo System<br>
<label class='checkbox'><input type="checkbox" id="optAccess2" value="leatherInt" onchange="processForm()"> Leather Interiors<br>
<label class='checkbox'><input type="checkbox" id="optAccess3" value="gpsSys" onchange="processForm()"> GPS System<br><br>
</td>

Related

Why does the total from last row is not calculating the sum?

I am doing a project that involves making an estimate and adding up does results. I am using the method GET and using some of the the info from the url. Also i am using WordPress to build the Web Page. Problem is that sum of the TOTAL column is not working and showing in the TOTAL row that i made. Is not an error but i think I need to add one more piece of code or change something in the javascript. So why does the id:"total" not showing the sum of the whole column? is the total.value wrong? does the id:"system_total" have a problem?
Here is how the HTML looks like:
<form >
<h2>Cotizacion</h2>
<table class="Cotization">
<tbody>
<tr>
<th style="width:25%;font-size:16px;text-align:center;">Description</th>
<th style="width:15%;" class="qtyhd" title="qtytt">Qty</th>
<th style="width:15%;" class="ratehd" title="ratett">Rate</th>
<th style="width:15%;" class="tlhd" title="totaltt">Total</th>
</tr>
<tr>
<td>PV Grid Tied System</td>
<td> <input id="system_qty" name="system_qty" value="1" type="number" /></td>
<td> <input id="system_rate" name="system_rate" value="0" type="number" /></td>
<td> <output id="system_total"> </output></td>
</tr>
<tr>
<td>Solar Modules 250w</td>
<td> <input id="modules_qty" name="modules_qty" value="0" type="number" /></td>
<td> <input id="modules_rate" name="modules_rate" value="0" type="number" /></td>
<td> <output id="modules_total"> </output></td>
</tr>
<tr>
<td>Inverter</td>
<td> <input id="inverter_qty" name="inverter_qty" value="1" type="number" /></td>
<td> <input id="inverter_rate" name="inverter_rate" value="0" type="number" /></td>
<td> <output id="inverter_total"> </output></td>
</tr>
<tr>
<td>Aluminum Fames</td>
<td> <input id="aluminum_qty" name="aluminum_qty" value="0" type="number" /></td>
<td> <input id="aluminum_rate" name="aluminum_rate" value="0" type="number" /></td>
<td> <output id="aluminum_total"> </output></td>
</tr>
<tr>
<td>Service Disconnect</td>
<td> <input id="servicedt_qty" name="servicedt_qty" value="1" type="number" /></td>
<td> <input id="servicedt_rate" name="servicedt_rate" value="0" type="number" /></td>
<td> <output id="servicedt_total"> </output></td>
</tr>
<tr>
<td>Installation</td>
<td> <input id="installation_qty" name="installation_qty" value="1" type="number" /></td>
<td> <input id="installation_rate" name="installation_rate" value="0" type="number" /></td>
<td> <output id="installation_total"> </output></td>
</tr>
<tr>
<td>Down Payment</td>
<td> <input id="dnpayment_qty" name="dnpayment_qty" value="-1" type="number" /></td>
<td> <input id="dnpayment_rate" name="dnpayment_rate" value="0" type="number" /></td>
<td> <output id="dnpayment_total"> </output></td>
</tr>
<tr>
<td>Total </td>
<td> </td>
<td> </td>
<td> <input id="total" name="total"/></td>
</tr>
</tbody>
</table>
</form>
And here is the javascript that might have the problem:
<script>
document.addEventListener('DOMContentLoaded', function () {
var system_size = Number(getParameterByName('system_size'));
var system_rate_input = document.getElementById('system_rate');
var modules_qty = document.getElementById('modules_qty');
var aluminum_qty = document.getElementById('aluminum_qty');
var systemTotal = Number(document.getElementById('system_total').innerText);
var moduleTotal = Number(document.getElementById('modules_total').innerText);
var inverterTotal = Number(document.getElementById('inverter_total').innerText);
var aluminumTotal = Number(document.getElementById('aluminum_total').innerText);
var servicedtTotal = Number(document.getElementById('servicedt_total').innerText);
var installationTotal = Number(document.getElementById('installation_total').innerText);
var dnpaymentTotal = Number(document.getElementById('dnpayment_total').innerText);
var total = document.getElementById('total');
modules_qty.value = Number(system_size) * 4;
aluminum_qty.value = Number(modules_qty.value);
system_rate_input.value = 2.9 * 1000 * 1.2 * system_size;
updateSystemTotal()
updateModulesTotal()
updateInverterTotal()
updateAluminumTotal()
updateServiceTotal()
updateInstallationTotal()
updateDownPaymentTotal()
total.value = Number(systemTotal) + Number(moduleTotal) + Number(inverterTotal) + Number(aluminumTotal) + Number(servicedtTotal) + Number(installationTotal) + Number(dnpaymentTotal);
})
// FIRST ROW
function updateSystemTotal() {
var output = document.getElementById('system_total');
var quantity = Number(document.getElementById('system_qty').value);
var system_rate = Number(document.getElementById('system_rate').value);
output.innerText = quantity * system_rate;
}
document.getElementById('system_rate').addEventListener('change', updateSystemTotal)
document.getElementById('system_qty').addEventListener('change', updateSystemTotal)
// Second ROW
function updateModulesTotal() {
var output = document.getElementById('modules_total');
var quantity = Number(document.getElementById('modules_qty').value);
var modules_rate = Number(document.getElementById('modules_rate').value);
output.innerText = quantity * modules_rate;
}
document.getElementById('modules_rate').addEventListener('change', updateModulesTotal)
document.getElementById('modules_qty').addEventListener('change', updateModulesTotal)
// Third ROW
function updateInverterTotal() {
var output = document.getElementById('inverter_total');
var quantity = Number(document.getElementById('inverter_qty').value);
var inverter_rate = Number(document.getElementById('inverter_rate').value);
output.innerText = quantity * inverter_rate;
}
document.getElementById('inverter_rate').addEventListener('change', updateInverterTotal)
document.getElementById('inverter_qty').addEventListener('change', updateInverterTotal)
// Fourth ROW
function updateAluminumTotal() {
var output = document.getElementById('aluminum_total');
var quantity = Number(document.getElementById('aluminum_qty').value);
var aluminum_rate = Number(document.getElementById('aluminum_rate').value);
output.innerText = quantity * aluminum_rate;
}
document.getElementById('aluminum_rate').addEventListener('change', updateAluminumTotal)
document.getElementById('aluminum_qty').addEventListener('change', updateAluminumTotal)
// Fith ROW
function updateServiceTotal() {
var output = document.getElementById('servicedt_total');
var quantity = Number(document.getElementById('servicedt_qty').value);
var servicedt_rate = Number(document.getElementById('servicedt_rate').value);
output.innerText = quantity * servicedt_rate;
}
document.getElementById('servicedt_rate').addEventListener('change', updateServiceTotal)
document.getElementById('servicedt_qty').addEventListener('change', updateServiceTotal)
// Six ROW
function updateInstallationTotal() {
var output = document.getElementById('installation_total');
var quantity = Number(document.getElementById('installation_qty').value);
var installation_rate = Number(document.getElementById('installation_rate').value);
output.innerText = quantity * installation_rate;
}
document.getElementById('installation_rate').addEventListener('change', updateInstallationTotal)
document.getElementById('installation_qty').addEventListener('change', updateInstallationTotal)
//Seventh ROW
function updateDownPaymentTotal() {
var output = document.getElementById('dnpayment_total');
var quantity = Number(document.getElementById('dnpayment_qty').value);
var dnpayment_rate = Number(document.getElementById('dnpayment_rate').value);
output.innerText = quantity * dtpayment_rate;
}
document.getElementById('dnpayment_rate').addEventListener('change', updateDownPaymentTotal)
document.getElementById('dnpayment_qty').addEventListener('change', updateDownPaymentTotal)
// DON't TOUCH ANYTHING BELOW THIS POINT!!!
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
</script>
var systemTotal = Number(document.getElementById('system').innerText);
There is no element called "system" in the snippets you provided. Are you sure you don't need to get the value from "system_total"?
Edit:
Total is showing 0 at the beginning, because the subtotals aren't initialized. To fix this, you can use your update functions before calculating the total.
document.addEventListener('DOMContentLoaded', function () {
var system_size = Number(getParameterByName('system_size'));
var system_rate_input = document.getElementById('system_rate');
var modules_qty = document.getElementById('modules_qty');
var aluminum_qty = document.getElementById('aluminum_qty');
var total = document.getElementById('total');
modules_qty.value = Number(system_size) * 4;
aluminum_qty.value = Number(modules_qty.value);
system_rate_input.value = 2.9 * 1000 * 1.2 * system_size;
updateSystemTotal();
updateModulesTotal();
updateInverterTotal();
updateAluminumTotal();
updateServiceTotal();
updateInstallationTotal();
updateDownPaymentTotal();
updateTotal();
})
function updateTotal() {
var total = document.getElementById('total');
var systemTotal = Number(document.getElementById('system_total').innerText);
var moduleTotal = Number(document.getElementById('modules_total').innerText);
var inverterTotal = Number(document.getElementById('inverter_total').innerText);
var aluminumTotal = Number(document.getElementById('aluminum_total').innerText);
var servicedtTotal = Number(document.getElementById('servicedt_total').innerText);
var installationTotal = Number(document.getElementById('installation_total').innerText);
var dnpaymentTotal = Number(document.getElementById('dnpayment_total').innerText);
total.value = Number(systemTotal) + Number(moduleTotal) + Number(inverterTotal) + Number(aluminumTotal) + Number(servicedtTotal) + Number(installationTotal) + Number(dnpaymentTotal);
}
Further, you are updating the subtotals as soon as the user edits Quantities or Rates, but you are not updating the "Total" value.
You could call updateTotal() in your own update functions to solve this issue:
function updateSystemTotal() {
var output = document.getElementById('system_total');
var quantity = Number(document.getElementById('system_qty').value);
var system_rate = Number(document.getElementById('system_rate').value);
output.innerText = quantity * system_rate;
updateTotal();
}
Copy my code and Run it :
javascript(1.js) :
function rr() {
var system_size = document.getElementById('system_qty').value;
var system_rate_input = document.getElementById('system_rate').value;
var modules_qty = document.getElementById('modules_qty').value;
var modules_rate = document.getElementById('modules_rate').value;
var inverter_qty = document.getElementById('inverter_qty').value;
var inverter_rate = document.getElementById('inverter_rate').value;
var aluminum_qty = document.getElementById('aluminum_qty').value;
var aluminum_rate = document.getElementById('aluminum_rate').value;
var servicedt_qty = document.getElementById('servicedt_qty').value;
var servicedt_rate = document.getElementById('servicedt_rate').value;
var installation_qty = document.getElementById('installation_qty').value;
var installation_rate = document.getElementById('installation_rate').value;
var dnpayment_qty = document.getElementById('dnpayment_qty').value;
var dnpayment_rate = document.getElementById('dnpayment_rate').value;
var systemTotal = system_size * system_rate_input;
document.getElementById('system_total').innerHTML = systemTotal;
var moduleTotal = modules_rate * modules_qty;
document.getElementById('modules_total').innerHTML = moduleTotal;
var inverterTotal = inverter_qty * inverter_rate;
document.getElementById('inverter_total').innerHTML = inverterTotal;
var aluminumTotal =aluminum_qty * aluminum_rate;
document.getElementById('aluminum_total').innerHTML = aluminumTotal;
var servicedtTotal = servicedt_qty * servicedt_rate;
document.getElementById('servicedt_total').innerHTML = servicedtTotal;
var installationTotal = installation_qty * installation_rate;
document.getElementById('installation_total').innerHTML = installationTotal;
var dnpaymentTotal = dnpayment_qty * dnpayment_rate;
document.getElementById('dnpayment_total').innerHTML = dnpaymentTotal;
var Total = document.getElementById('total');
aluminum_qty = system_size * 4;
system_rate_input = 2.9 * 1000 * 1.2 * system_size;
Total.value = systemTotal + moduleTotal + inverterTotal+ aluminumTotal + servicedtTotal+ installationTotal + dnpaymentTotal;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="1.js"></script>
<form name="frm" >
<h2>Cotizacion</h2>
<table class="Cotization">
<tbody>
<tr>
<th style="width:25%;font-size:16px;text-align:center;">Description</th>
<th style="width:15%;" class="qtyhd" title="qtytt">Qty</th>
<th style="width:15%;" class="ratehd" title="ratett">Rate</th>
<th style="width:15%;" class="tlhd" title="totaltt">Total</th>
</tr>
<tr>
<td>PV Grid Tied System</td>
<td> <input id="system_qty" name="system_qty" value="1" type="number" /></td>
<td> <input id="system_rate" name="system_rate" value="0" type="number" /></td>
<td> <output id="system_total"> </output></td>
</tr>
<tr>
<td>Solar Modules 250w</td>
<td> <input id="modules_qty" name="modules_qty" value="0" type="number" /></td>
<td> <input id="modules_rate" name="modules_rate" value="0" type="number" /></td>
<td> <output id="modules_total"> </output></td>
</tr>
<tr>
<td>Inverter</td>
<td> <input id="inverter_qty" name="inverter_qty" value="1" type="number" /></td>
<td> <input id="inverter_rate" name="inverter_rate" value="0" type="number" /></td>
<td> <output id="inverter_total"> </output></td>
</tr>
<tr>
<td>Aluminum Fames</td>
<td> <input id="aluminum_qty" name="aluminum_qty" value="0" type="number" /></td>
<td> <input id="aluminum_rate" name="aluminum_rate" value="0" type="number" /></td>
<td> <output id="aluminum_total"> </output></td>
</tr>
<tr>
<td>Service Disconnect</td>
<td> <input id="servicedt_qty" name="servicedt_qty" value="1" type="number" /></td>
<td> <input id="servicedt_rate" name="servicedt_rate" value="0" type="number" /></td>
<td> <output id="servicedt_total"> </output></td>
</tr>
<tr>
<td>Installation</td>
<td> <input id="installation_qty" name="installation_qty" value="1" type="number" /></td>
<td> <input id="installation_rate" name="installation_rate" value="0" type="number" /></td>
<td> <output id="installation_total"> </output></td>
</tr>
<tr>
<td>Down Payment</td>
<td> <input id="dnpayment_qty" name="dnpayment_qty" value="-1" type="number" /></td>
<td> <input id="dnpayment_rate" name="dnpayment_rate" value="0" type="number" /></td>
<td> <output id="dnpayment_total"> </output></td>
</tr>
<tr>
<td>Total </td>
<td> </td>
<td> </td>
<td> <input value="" id="total" name="total"/></td>
</tr>
</tbody>
</table>
</form>
<button id="btn" onclick="rr()">Click</button>
</body>
</html>

Get sum of radio button value using javascript function in table

I am looking to get the sum of these 4 different values without query through a the radio buttons.
Here my javascript and html, once I click on submit, 0 appears in the total field, thank you for your help!
<!DOCTYPE html>
<html>
<body>
<script>
function checkRadio() {
var selectedAge="";
var selectedBmi="";
var selectedDiabete="";
var description="";
var len = document.row.length;
var i;
function init(){
for (i = 0; i<len; i++) {
if (document.row[i].value);
break;
}
if (selectedAge == "") {
document.getElementByid("radio_error").innnerHTML = "no option selected";
return false
}
else {
document.getElementById("radio_error").innerHTML = "";
return true;
}
}
init();
}
</script>
<script>
function addNumbers()
{
var val1 = parseInt(document.getElementById("value1").value);
var val2 = parseInt(document.getElementById("value2").value);
var val3 = parseInt(document.getElementById("value3").value);
var val4 = parseInt(document.getElementById("value4").value);
var ansD = document.getElementById("answer");
ansD.value = val1 + val2 + val3 + val4;
}
</script>
<table>
<tr>
<th scope="col"></th>
<th scope="col">noRisk</th>
<th scope="col">lowRisk</th>
<th scope="col">mediumRisk</th>
<th scope="col">HighRisk</th>
</tr>
<tr>
<th scope="row"><div class="lefttext">How old are you?</div></th>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="0"checked>1-25</td>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="5">26-40</td>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="8">41-60</td>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="10">1-25</td>
</tr>
<tr>
<th scope="row"><div class="lefttext">What is you BMI?</div></th>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="0" checked>0-25</td>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="0">26-30</td>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="9">31-35</td>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="10">35+</td>
</tr>
<tr>
<th scope="row"><div class="lefttext">Does anybody in your family have diabetes?</div></th>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="0" checked>No</td>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="7">Grandparent</td>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="15">Sibling</td>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="15">Parent</td>
</tr>
<tr>
<th scope="row"><div class="lefttext">How would you describe your diabete</div></th>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="0" checked >Low sugar</td>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="0">Normal sugar</td>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="7">Quite high sugar</td>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="10">High sugar</td>
</tr>
</table>
<input type="button" name="Sumbit" value="Submit" onclick="javascript:addNumbers()"/>
Total = <input type="text" id="answer" name="answer" value=""/>
</body>
You have to specify that you only want the value of the checked checkboxes. You now select all the checkboxes. Try this instead:
function addNumbers()
{
var val1 = parseInt(document.querySelector('input[name = "selectedAge"]:checked').value);
var val2 = parseInt(document.querySelector('input[name = "selectedBmi"]:checked').value);
var val3 = parseInt(document.querySelector('input[name = "selectedDiabete"]:checked').value);
var val4 = parseInt(document.querySelector('input[name = "description"]:checked').value);
var ansD = document.getElementById("answer");
ansD.value = val1 + val2 + val3 + val4;
}
Here is working example.
Basically:
var sum = function(a, b) {
return a + b;
};
var getPollResult = function() {
var checkedRadioButtons = document.querySelectorAll('table input[type="radio"]:checked');
return Array.prototype.map.call(checkedRadioButtons, function(radio) { return parseInt(radio.value, 10); }).reduce(sum, 0);
};
document.getElementById("submit").addEventListener('click', function() {
document.getElementById("answer").value = getPollResult();
});

add value to total if radio box checked

There is something not working at this script.
I need when check one radio button to add the amount at the total price.
This is doing well, but if I check different radio buttons, it ads all of them.
If I have total = 100$; and button1=10$, button2=10$, button3=10$
and if I check all 3... I will get total = 130$ instead of 110$
function calculateTotal(payment)
{
var check=document.getElementById("check").value;
var city = document.getElementsByName('loc');
var value= payment.value;
var total= document.getElementById("totl").value;
var tcharge;
var pvcharge=document.getElementById("ch").value;
if(value==0 && check==0)
return;
if(value==0 && check==1)
{
total= parseFloat(parseFloat(total)-parseFloat(pvcharge)).toFixed(2);
tcharge=0;
}else
{
if(total>=200)
return;
if(value=='online' || value =='transfer_bancar' || value=='cash' || value == 'la_sediul_nostru')
{
if(city[0].checked)
{
total= parseFloat(parseFloat(total)+15.0).toFixed(2);
tcharge=15.00;
}
else
if(city[1].checked)
{
total= parseFloat(parseFloat(total)+30.0).toFixed(2);
tcharge=30.00;
}
}
else
if(value='la_expeditor')
{
if(city[0].checked)
{
total= parseFloat(parseFloat(total)+30.0).toFixed(2);
tcharge=30.00;
}
else
if(city[1].checked)
{
total= parseFloat(parseFloat(total)+60.0).toFixed(2);
tcharge=60.00;
}
}
}
document.getElementById("tot").innerHTML=total+" LEI";
document.getElementById("totl").value=total;
document.getElementById("amt").value=total;
document.getElementById("tcharge").innerHTML=tcharge+" LEI";
document.getElementById("check").value=1;
document.getElementById("ch").value=tcharge;
}
radio box
<tr>
<td colspan="2"> <input type="radio" name="payment" value="online" id="online" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdadasdad</b></span></td>
</tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="transfer_bancar" id="bancar" onClick="calculateTotal(this); return bancarval();" /> <span class="fontext"><b>asdadadadasd</b></span></td>
</tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="cash" onClick="calculateTotal(this);return empty();" /> <span class="fontext"><b>asdadadadadad</b></span></td>
</tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="la_expeditor" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdadasdadad</span></td> </tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="la_sediul_nostru" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdadasdad</b></span></td>
</tr>
<tr>
<tr>
<td colspan="2"> <input type="radio" name="payment" value="0" onClick="calculateTotal(this); return empty();" /> <span class="fontext"><b>asdasdasd</b></span></td> </tr>
<tr>
<td><span class="fontext"><b>Cost transport: </b></span></td> <td><span class="fontext" ><b id="tcharge">0.00 LEI</b></span></td> </tr>
and php
if($Tott<200)
if(isset($_POST['loc']))
{
$tcharges=$_POST['loc'];
if(isset($_POST['payment']))
{
$payment=$_POST['payment'];
if($payment!=0)
if($payment=='online' || $payment =='transfer_bancar' || $payment=='cash' || $payment == 'la_sediul_nostru')
{
if($tcharges=='in')
$Tott+=15;
else
$Tott+=30;
}else
if($payment=='la_expeditor')
{
if($tcharges=='in')
$Tott+=30;
else
$Tott+=60;
}
}
}
Each time, you're operating off the total of the previous calculation.
Offending line:
var total= document.getElementById("totl").value;
Instead, change it to operate off the original, clean value.

Javascript Form Validation won't validate

I'm having some issues validating my form. When I click to validate, it doesn't do anything other than refocus the page the first time, and the second time the page continues to the server. I've been looking for a few hours trying to find what the problem is, but I just can't see it.
Here is my Javascript code:
function formValidation() {
var uname = document.GetElementByName("UserName");
var uname = document.joinform.UserName;
var password = document.joinform.Password;
var fname = document.joinform.firstname;
var mname = document.joinform.middlename;
var lname = document.joinform.lastname;
var unationality = document.joinform.nationality;
var ulcontact = document.joinform.lpreferredcontact;
var umcontact = document.joinform.mpreferredcontact;
var uecontact = document.joinform.epreferredcontact;
var ulandline = document.joinform.dayphone;
var umobile = document.joinform.mobphone;
var uemail = document.joinform.email;
var uadd1 = document.joinform.address1;
var uadd2 = document.joinform.address2;
var upostcode = document.joinform.postcode;
var city = document.joinform.city;
var state = document.joinform.state;
var occupation = document.joinform.occupation;
var hobbies = document.joinform.hobbies;
var interest = document.joinform.interest;
if (username_validation(uname, 20, 20)) {
} else {
return false;
}
{
if (username_validation(uname, 20, 20)) {
if (password_validation(password, 20, 20)) {
if (allLetter(fname)) {
if (allLetter(mname)) {
}
}
}
}
return false;
}
if(username_validation(uname,20,20)) {
if(passid_validation(password,20,20)) {
if(allLetter(fname)) {
if(allLetter(mname)) {
if(allLetter(lname)) {
if(allLetter(unationality)) {
if(validcontact(ulcontact,umcontact,uecontact)) {
if(allnumeric(ulandline)) {
if(allnumeric(umobile)) {
if(ValidateEmail(uemail)) {
if(alphanumeric(uadd1)) {
if(alphanumeric(uadd2)) {
if(allnumeric(upostcode)) {
if(allLetter(city)) {
if(stateselect(state)) {
if(allLetter(occupation)) {
if(allLetter(hobbies)) {
if(interestselect(interest)) {
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
function username_validation(uname,mx,my)
{
var uname_len = uname.value.length;
if (uname_len >= my || uname_len < mx)
{
alert("User name length should be between "+mx+" to "+my);
uname.focus();
return false;
}
return true;
}
function password_validation(password,mx,my)
{
var password_len = password.value.length;
if (password_len >= my || password_len < mx)
{
alert("Password length should be between "+mx+" to "+my);
password.focus();
return false;
}
return true;
}
function allLetter(fname)
{
var letters = /^[A-Za-z]+$/;
if(fname.value.match(letters))
{
return true;
}
else
{
alert('First name must have alphabet characters only');
fname.focus();
return false;
}
}
function allLetter(mname)
{
var letters = /^[A-Za-z]+$/;
if(mname.value.match(letters))
{
return true;
}
else
{
alert('Middle name must have alphabet characters only');
mname.focus();
return false;
}
}
function allLetter(lname)
{
var letters = /^[A-Za-z]+$/;
if(lname.value.match(letters))
{
return true;
}
else
{
alert('Last name must have alphabet characters only');
lname.focus();
return false;
}
}
function allLetter(unationality)
{
var letters = /^[A-Za-z]+$/;
if(unationality.value.match(letters))
{
return true;
}
else
{
alert('Nationality must have alphabet characters only');
unationality.focus();
return false;
}
}
function validcontact(ulcontact,umcontact,uecontact)
{
x=0;
if(ulcontact.checked)
{
x++;
}
if(umcontact.checked)
{
x++;
} if(uecontact.checked)
{
x++;
}
if(x==0)
{
alert('Select the preferred Contact method');
ulcontact.focus();
return false;
}
function allnumeric(ulandline)
{
var numbers = /^[0-9]+$/;
if(ulandline.value.match(numbers))
{
return true;
}
else
{
alert('landline number must have numeric characters only');
ulandline.focus();
return false;
}
}
function allnumeric(umobile)
{
var numbers = /^[0-9]+$/;
if(umobile.value.match(numbers))
{
return true;
}
else
{
alert('mobile number must have numeric characters only');
umobile.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
}
function alphanumeric(uadd1)
{
var letters = /^[0-9a-zA-Z]+$/;
if(uadd1.value.match(letters))
{
return true;
}
else
{
alert('User address must have alphanumeric characters only');
uadd1.focus();
return false;
}
}
function alphanumeric(uadd2)
{
var letters = /^[0-9a-zA-Z]+$/;
if(uadd2.value.match(letters))
{
return true;
}
else
{
alert('User address must have alphanumeric characters only');
uadd2.focus();
return false;
}
}
function allnumeric(postcode)
{
var numbers = /^[0-9]+$/;
if(postcode.value.match(numbers))
{
return true;
}
else
{
alert('postcode must have numeric characters only');
postcode.focus();
return false;
}
}
function allLetter(city)
{
var letters = /^[A-Za-z]+$/;
if(city.value.match(letters))
{
return true;
}
else
{
alert('City must have alphabet characters only');
city.focus();
return false;
}
}
function stateselect(state)
{
if(state.value == "Default")
{
alert('Select your state from the list');
state.focus();
return false;
}
else
{
return true;
}
}
function allLetter(occupation)
{
var letters = /^[A-Za-z]+$/;
if(occupation.value.match(letters))
{
return true;
}
else
{
alert('Occupation must have alphabet characters only');
occupation.focus();
return false;
}
}
function allLetter(hobbies)
{
var letters = /^[A-Za-z]+$/;
if(hobbies.value.match(letters))
{
return true;
}
else
{
alert('Hobbies must have alphabet characters only');
hobbies.focus();
return false;
}
}
function interestselect(interest) {
if (interest.value == "Default") {
alert('Select your interest from the list');
interest.focus();
return false;
}
else {
alert('Form is Successfully Submitted, thank you');
window.location.reload()
return true;
}
}
Here is my html code:
<form action="http://******/cgi-bin/echo_form" method="post" name="joinform" onsubmit="return check_compulsory(joinform);">
<form action="http://********/cgi-bin/echo_form" method="post" name="joinform" onsubmit="return formValidation();">
<form name="loginform" onsubmit="return loginValidation();">
<table style="margin: 0px auto;">
<tr>
<td>UserName:</td>
<td><input type="text" name="UserName" value="" size="20" maxlength="40" /></td>
<td></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="Password" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
</table>
<div style=margin-left:475px;>
<input type="submit" value="Sign In" />
</div>
</form>
<br>
<h1>Join Us Today!</h1>
<p>Please complete this simple form to Sign Up to CWON-Australia!</p>
<p style=color:blue;>*CompulsoryField</p>
<form action="http://******/cgi-bin/echo_form" method="post" name="joinform" onsubmit="return check_compulsory(joinform);">
<form action="http://******/cgi-bin/echo_form" method="post" name="joinform" onsubmit="return formValidation()">
<form name="joinform" onsubmit="return formValidation()">
<table>
<tr>
<td>First Name:*</td>
<td><input type="text" name="firstname" value="" size="20" maxlength="40" /></td>
<td></td>
</tr>
<tr>
<td>Middle Name:</td>
<td><input type="text" name="middlename" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>Last Name:*</td>
<td><input type="text" name="lastname" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>Date Of Birth*</td>
<td><input type="text" name="dateofbirth" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>Nationality</td>
<td><input type="text" name="nationality" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>Preferred Contact Method: *</td>
<td><input type="radio" name="preferredcontact" id="cl" value="L" /> Landline</td>
</tr>
<tr>
<td></td>
<td><input type="radio" name="preferredcontact" id="cm" value="M" /> Mobile</td>
</tr>
<tr>
<td></td>
<td><input type="radio" name="preferredcontact" id="ce" value="E" checked="checked" /> E-Mail</td>
</tr>
<tr>
<td>Landline Phone Number:</td>
<td><input type="text" name="dayphone" value="" size="20" maxlength="20" /></td>
</tr>
<tr>
<td>Mobile Phone Number:</td>
<td><input type="text" name="mobphone" value="" size="20" maxlength="20" /></td>
</tr>
<tr>
<td>e-Mail Address: *</td>
<td><input type="text" name="email" value="" size="30" maxlength="30" /></td>
</tr>
<tr>
<td>Address Line 1: *</td>
<td><input type="text" name="address1" value="" size="40" maxlength="40" /></td>
</tr>
<tr>
<td>Address Line 2: *</td>
<td><input type="text" name="address2" value="" size="40" maxlength="40" /></td>
<td></td>
</tr>
<tr>
<td>Postcode: *</td>
<td><input type="text" name="postcode" value="" size="4" maxlength="4" /></td>
<td></td>
</tr>
<tr>
<td>City: *</td>
<td><input type="text" name="city" value="" size="25" maxlength="25" /></td>
<td></td>
</tr>
<tr>
<td>State: *</td>
<td>
<select name="state" size="1">
<option selected = "selected">Please Choose</option>
<option>NSW</option>
<option>VIC</option>
<option>WA</option>
<option>SA</option>
<option>TAS</option>
<option>QLD</option>
<option>ACT</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td>Occupation:</td>
<td><input type="text" name="occupation" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>Hobbies:</td>
<td><input type="text" name="hobbies" value="" size="20" maxlength="60" /></td>
<td></td>
</tr>
<tr>
<td>You Are Interested in:* </td>
<td>
<select name="interest" size="1">
<option selected = "selected">Please Choose</option>
<option>Fund Raisers</option>
<option>Domestic Volunteering</option>
<option>Foreign Volunteering</option>
<option>All of Them</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" name="TandC" id="TandC" value="yes" checked="checked"> </td>
<td>I have read the Terms & Conditions of being the member of CWON-Australia, and I agree to abide by the rules and regulations.</td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" name="newsletter" id="newsletter" value="yes" checked="checked"></td>
<td>Sign Up for CWON-Australia Newsletter.</td>
<td></td>
</tr>
<tr>
<td></td>
<td><input type="hidden" name="signupdate" value="" /></td>
<td></td>
</tr>
</table>
<div align="right">
<input type="reset" value="Reset" onclick="set_focus()" />
<input type="submit" value="Join Now!" />
</div>
</form>
Delete all your messy code and try jQuery.validate or Really simple validation .
You are welcome~
Check out AngularJS. If you're writing large javascript-oriented web applications it can make your life a lot easier.

how to show an alert after validation but before submission

I have all of my validation code figured out but I'm not quite sure on how to code an alert to pop up before the form is submitted but after the validation is complete.
<!DOCTYPE html>
<html>
<head>
<title>Week 8 Lab - JavaScript DOM and Arrays</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validate()
{
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if(lName==null || lName=="")
{
document.getElementById('lastNameError').innerHTML= "Please enter a last name.";
return false;
}
var address = document.forms["orderForm"].address.value;//address validation
if(address==null || address=="")
{
document.getElementById('addressError').innerHTML= "Please enter an address.";
return false;
}
var city = document.forms["orderForm"].city.value;//city validation
if(city==null || city=="")
{
document.getElementById('cityError').innerHTML= "Please enter a city.";
return false;
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if(postalCode.value.match(pCodeCheck))
{
//do nothing
return true;
}
else
{
document.getElementById('postalCoderror').innerHTML= "Please enter a valid postal code.";
return false;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if(itemQTY < 0)
{
document.getElementById('qtyError').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if(itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if(itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML= "You cannot enter a negative number.";
return false;
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if(wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML= "You must order atleast one item.";
return false;
}
/*
// trying to send alert with the order total.
// not sure how to call it after the validation is done.
var total1;
var total2;
var total3:
var total4;
if(document.getElementById('widget1qty').value == 0)
{
total1 = 0;
}
else(document.getElementById('widget1qty').value != 0)
{
total1 = document.getElementById('widget1qty').value * 5;
}
if(document.getElementById('widget2qty').value == 0)
{
total2 = 0;
}
else(document.getElementById('widget2qty').value != 0)
{
total2 = document.getElementById('widget2qty').value * 15;
}
if(document.getElementById('widget3qty').value == 0)
{
total3 = 0;
}
else(document.getElementById('widget3qty').value != 0)
{
total3 = document.getElementById('widget3qty').value * 25;
}
total4 = (total1 + total2 + total3)
alert('Your total is: $' + total4 + '.00');
*/
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" onsubmit="validate();" action="processForm.html">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Québec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr></tr><tr></tr><tr></tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<td><input type="submit" name="btnSubmit" id="btnSubmit" onclick="return validate();" value="Submit Order"></td>
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
I just don't know how to code it to pop up after the validation is complete.
In your form, you could put anid = "myForm"and then do this in javascript:
function validateForm() {
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if(lName==null || lName=="")
{
document.getElementById('lastNameError').innerHTML= "Please enter a last name.";
return false;
}
var address = document.forms["orderForm"].address.value;//address validation
if(address==null || address=="")
{
document.getElementById('addressError').innerHTML= "Please enter an address.";
return false;
}
var city = document.forms["orderForm"].city.value;//city validation
if(city==null || city=="")
{
document.getElementById('cityError').innerHTML= "Please enter a city.";
return false;
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if(postalCode.value.match(pCodeCheck))
{
//do nothing
return true;
}
else
{
document.getElementById('postalCoderror').innerHTML= "Please enter a valid postal code.";
return false;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if(itemQTY < 0)
{
document.getElementById('qtyError').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if(itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if(itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML= "You cannot enter a negative number.";
return false;
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if(wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML= "You must order atleast one item.";
return false;
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3)
alert('Your total is: $' + total4 + '.00');
return;
}
function startValidate(){
validateForm();
document.forms['orderForm'].submit();
}
Edit:
Just add all the other info in the validateForm() function.
I did't seen it because I started my edit before you added the HTML and the other JS.
According to War10ck's post you should change this :
<input type="submit" name="btnSubmit" id="btnSubmit" onsubmit="startValidate()" value="Submit Order">
You can make another function called FireOnSubmit and do something like this:
`
function FireOnSubmit(){
if(validate()==true) alert(""form validated..is being redirected")
else {
alert("invalid form data");
return false;
}
}
`
You can put FireOnSubmit on the onsubmit of the form instead of the validate function.
Also, you will need to return true or false from your validate function.
Instead of all that JavaScript, this should work just as well.
The submit button cannot be clicked until all fields you pick have been filled.
Then a alert pops up with your message.
This Goes In The Head Section
<script>
function checkform()
{
var f = document.forms["testform"].elements;
var cansubmit=true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length==0) cansubmit=false;
}
if (cansubmit)
{
document
.getElementById('submit'
).disabled=false;
}
}
</script>
Here Is The Form. The Submit Button Is Disabled Until All Fields Are Filled.
<form name="testform">
<input type="text" onKeyup="checkform()" placeholder="First Name"required/><br>
<input type="text" onKeyup="checkform()" placeholder="Last Name" required/><br>
<input id="submit" type="submit" disabled="disabled" value="Submit" onclick="alert('Your Alert Here...')"/>
</form>

Categories

Resources