I have not posted on Stack in a long time so my apologies if my question is missing any obvious details for a solution.
Here is my problem: I have an html table with 20 rows, 5 columns of textboxes in each row. I have the rows populating values in 3 specific textboxes (Total pipes, total fitting, total other items) using the 'onchange' event in javascript functions. The way it works is you type in either 'pipe', 'fitting', or 'other' in a textbox, then you select the value 1,2,3,4, or 5 from a select drop-down. The select drop-down has an 'onchange' event. The 'onchange event then populates another textbox with 'total pipes being ordered' , 'total fitting items' being ordered or 'total other items ordered' based on if you typed 'pipe', 'fitting' or 'other' and which row you indicated this in.
For example, if you select 'pipes' and a quantity of '3' in row 1, then select 'pipes' and a quantity of '5' in row 7, the value in the 'total pipes' textbox has to show '8'.
My code is going to get out of hand quickly the direction I am going and I am sure there is a much simpler way to make this week. Any help is appreciated.
Below is my code:
HTML
<table id="mainTbl1">
<tr>
<th><input type="text" id="txtItemBox" value="Item#" readonly=true></th>
<th><input type="text" id="txtItemBox" value="Item Type?" readonly=true> </th>
<th><input type="text" id="txtItemBox" value="Quantity" readonly=true></th>
<th><input type="text" id="txtItemBox" value="Size" readonly=true></th>
<th><input type="text" id="txtItemBox" value="Description" readonly=true></th>
<th><input type="text" id="txtItemBox" value="Unit Price" readonly=true></th>
<th><input type="text" id="txtItemBox" value="Extend Price" readonly=true></th></tr>
<tr>
<td><input type="text" id="" value="1" /></td>
<td><input type="text" id="seltype" /></td>
<td><select id="txtItemBoxVal2" onchange="populateUPrice()">
<option value="0">-----</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
<td><input type="text" id="" /></td>
<td><input type="text" id="" /></td>
<td><input type="text" id="txt2" /></td>
<td><input type="text" id="txt2e" /></td>
</tr>
<tr>
<td><input type="text" id="" value="2" /></td>
<td><input type="text" id="seltype2" /></td>
<td><select id="txtItemBoxVal3" onchange="populateUPrice2()">
<option value="0">-----</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
<td><input type="text" id="" /></td>
<td><input type="text" id="" /></td>
<td><input type="text" id="txt3" /></td>
<td><input type="text" id="txt3e" /></td>
</tr>
JavaScript
<script type="text/javascript">
var stotal;
var s1, s2, s3, t1, t2, t3;
function populateUPrice() {
// declare variable to hold quantity amount
s1 = document.getElementById("txtItemBoxVal2").value;
t1 = document.getElementById("seltype").value;
stotal = s1;
if (t1 == "pipe") {
document.getElementById("seltype").innerHTML = "pipe"
document.getElementById("pipeFt").value = s1;
document.getElementById("fittingsCt").value = "";
document.getElementById("otherVal").value = "";
} else if (t1 == "fitting") {
document.getElementById("seltype").innerHTML = "fitting"
document.getElementById("fittingsCt").value = s1;
document.getElementById("pipeFt").value = "";
document.getElementById("otherVal").value = "";
} else if (t1 == "other") {
document.getElementById("seltype").innerHTML = "other"
document.getElementById("otherVal").value = s1;
document.getElementById("pipeFt").value = "";
document.getElementById("fittingsCt").value = "";
}
if (document.getElementById("txtItemBoxVal2")) {
document.getElementById("txt2").value = "0.00"
}
}
function populateUPrice2() {
// declare variable to hold quantity amount
s2 = document.getElementById("txtItemBoxVal3").value;
t2 = document.getElementById("seltype2").value;
stotal = parseInt(s1) + parseInt(s2);
if (t1 == "pipe" && t2 == "pipe") {
document.getElementById("seltype2").innerHTML = "pipe"
document.getElementById("pipeFt").value = parseInt(stotal);
document.getElementById("fittingsCt").value = "";
document.getElementById("otherVal").value = "";
} else if (t1 == "fitting" && t2 == "fitting") {
document.getElementById("seltype2").innerHTML = "fitting"
document.getElementById("fittingsCt").value = parseInt(stotal);
document.getElementById("pipeFt").value = "";
document.getElementById("otherVal").value = "";
} else if (t1 == "other" && t2 == "other") {
document.getElementById("seltype2").innerHTML = "other"
document.getElementById("otherVal").value = parseInt(stotal);
document.getElementById("pipeFt").value = "";
document.getElementById("fittingsCt").value = "";
} else if (t1 == "pipe" && t2 == "fitting") {
document.getElementById("pipeFt").value = s1;
document.getElementById("fittingsCt").value = s2;
document.getElementById("otherVal").value = "";
} else if (t1 == "pipe" && t2 == "other") {
document.getElementById("pipeFt").value = s1;
document.getElementById("fittingsCt").value = "";
document.getElementById("otherVal").value = s2;
} else if (t1 == "fitting" && t2 == "pipe") {
document.getElementById("pipeFt").value = s2;
document.getElementById("fittingsCt").value = s1;
document.getElementById("otherVal").value = "";
} else if (t1 == "fitting" && t2 == "other") {
document.getElementById("pipeFt").value = "";
document.getElementById("fittingsCt").value = s1;
document.getElementById("otherVal").value = s2;
} else if (t1 == "other" && t2 == "pipe") {
document.getElementById("pipeFt").value = s2;
document.getElementById("fittingsCt").value = "";
document.getElementById("otherVal").value = s1;
} else if (t1 == "other" && t2 == "fitting") {
document.getElementById("pipeFt").value = "";
document.getElementById("fittingsCt").value = s2
document.getElementById("otherVal").value = s1;
}
if (document.getElementById("txtItemBoxVal3")) {
document.getElementById("txt3").value = "0.00";
}
}
Related
By choosing the version of the product, a price populates the cell of "unit" ... working good so far.
But when I choose the quantity "Qt", I wanted the field "Price" to be populated by multiplying (unit*Price).
enter image description here
function showVersions() {
var selectBox = document.getElementById('gcard');
var userInput = selectBox.options[selectBox.selectedIndex].value;
if (userInput == 'nvidia') {
document.getElementById("nvidiaversion").style = "visibility: visible;";
} else if (userInput == 'amd') {
document.getElementById("amdversion").style = "visibility: visible;";
}
return false;
}
function itemPrice1() {
var nvidiaItem = document.getElementById('nvidiaversion');
var nvidiaInput = nvidiaItem.options[nvidiaItem.selectedIndex].value;
if (nvidiaInput == 'gtx300') {
var gtx300 = document.getElementById("unit");
gtx300.innerHTML = 300;
} else if (nvidiaInput == 'fgt4000') {
var fgt4000 = document.getElementById("unit");
fgt4000.innerHTML = 1000;
}
return false;
}
function itemPrice2() {
var amdItem = document.getElementById('amdversion');
var amdInput = amdItem.options[amdItem.selectedIndex].value;
if (amdInput == 'amd20') {
var amd20 = document.getElementById("unit");
amd20.innerHTML = 369;
} else if (amdInput == 'krt30') {
var krt30 = document.getElementById("unit");
krt30.innerHTML = 200;
}
return false;
}
function quantity() {
var quantity = document.getElementById('quantity');
var qtInput = quantity.options[quantity.selectedIndex].value;
var unit = document.getElementById("unit").value;
if (qtInput == "1") {
var qt1 = document.getElementById("price");
qt1.innerHTML = 1 * unit;
} else if (qtInput == "2") {
var qt2 = document.getElementById("price");
qt2.innerHTML = 2 * unit;
}
return false;
}
<table>
<tr>
<th> Items </th>
<th> Unit </th>
<th> Qt </th>
<th> Price </th>
</tr>
<tr>
<td name="items">
<div>
<select name="gcard" id="gcard" onchange="return showVersions();">
<option value="nvidia">NVIDIA</option>
<option value="amd">AMD</option>
</select>
</div>
<div>
<select name="gcard" id="nvidiaversion" style="visibility: hidden;" onchange="itemPrice1();">
<option value="gtx300">GTX 300</option>
<option value="fgt4000">FGT 4000</option>
</select>
</div>
<div>
<select name="gcard" id="amdversion" style="visibility: hidden;" onchange="itemPrice2();">
<option value="amd20">AMD 20</option>
<option value="krt30">KRT 30</option>
</select>
</div>
</td>
<td id="unit">
</td>
<td name="quantity">
<div>
<select name="quantity" id="quantity" onchange="quantity();">
<option value="0">Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</td>
<td id="price">
</td>
</tr>
</table>
I believe something is missing im the"function quantity", but i can't get it.
NB : I need to make it work without using arrays.
td does not have value, try textContent.
Change:
var unit = document.getElementById("unit").value;
To:
var unit = document.getElementById("unit").textContent;
function showVersions(){
var selectBox = document.getElementById('gcard');
var userInput = selectBox.options[selectBox.selectedIndex].value;
if (userInput == 'nvidia') {
document.getElementById("nvidiaversion").style="visibility: visible;";
} else if (userInput == 'amd') {
document.getElementById("amdversion").style="visibility: visible;";
}
return false;
}
function itemPrice1(){
var nvidiaItem = document.getElementById('nvidiaversion');
var nvidiaInput = nvidiaItem.options[nvidiaItem.selectedIndex].value;
if (nvidiaInput == 'gtx300'){
var gtx300 = document.getElementById("unit");
gtx300.innerHTML = 300;
}else if (nvidiaInput == 'fgt4000'){
var fgt4000 = document.getElementById("unit");
fgt4000.innerHTML = 1000;
}
return false;
}
function itemPrice2(){
var amdItem = document.getElementById('amdversion');
var amdInput = amdItem.options[amdItem.selectedIndex].value;
if (amdInput == 'amd20'){
var amd20 = document.getElementById("unit");
amd20.innerHTML = 369;
}else if (amdInput == 'krt30'){
var krt30 = document.getElementById("unit");
krt30.innerHTML = 200;
}
return false;
}
function quantity(){
var quantity = document.getElementById('quantity');
var qtInput = quantity.options[quantity.selectedIndex].value;
var unit = document.getElementById("unit").textContent;
if (qtInput == "1"){
var qt1 = document.getElementById("price");
qt1.innerHTML = 1*unit;
}else if (qtInput == "2"){
var qt2 = document.getElementById("price");
qt2.innerHTML = 2*unit;
}
return false;
}
<table>
<tr>
<th> Items </th>
<th> Unit </th>
<th> Qt </th>
<th> Price </th>
</tr>
<tr>
<td name="items">
<div>
<select name="gcard" id="gcard" onchange="return showVersions();">
<option value="nvidia">NVIDIA</option>
<option value="amd">AMD</option>
</select>
</div>
<div>
<select name="gcard" id="nvidiaversion" style="visibility: hidden;" onchange="itemPrice1();">
<option value="gtx300">GTX 300</option>
<option value="fgt4000">FGT 4000</option>
</select>
</div>
<div>
<select name="gcard" id="amdversion" style="visibility: hidden;" onchange="itemPrice2();">
<option value="amd20">AMD 20</option>
<option value="krt30">KRT 30</option>
</select>
</div>
</td>
<td id="unit">
</td>
<td name="quantity">
<div>
<select name="quantity" id="quantity" onchange="quantity();">
<option value="0">Quantity</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</td>
<td id="price">
</td>
</tr>
</table>
I would like to calculate the line total for each item using the itemPrice* Qty fields, the line amount is to be auto populated in the linePrice textbox. After which the grand total is then auto populated to the priceTotal field by summing up all the line prices.
I am having a challenge getting each Qty and itemPrice textbox value into my JavaScript function since the name(s) is/are Qty0, Qty1, Qty2... and itemPrice0, itemPrice1,.. depending on the added row, and also getting the final calculations into the respective textboxes.
Below is my code.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
return false;
return true;
}
$(document).ready(function() {
$(document).on("keyup", ".Qty", calculateTot);
$("button").click(function() {
addrow('tb')
});
});
function calculateTot() {
var sum = 0;
var price = document.getElementById('itemPrice').value;
var qtyPur = parseFloat(this.value);
$(".Qty").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
linePR = price * qtyPur;
}
});
$("#linePrice").val(linePR.toFixed(2));
calculateSum();
}
function calculateSum() {
var sum = 0;
$(".linePrice").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#priceTotal").val(sum.toFixed(2));
}
$(document).ready(function() {
var i = 1,
j = 1;
$("#add_row").click(function() {
if (i < 10) {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");
$('#tab_add').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
j++;
$('#delete_row').show();
} else {
alert("You can only add upto a maximum of 10 items")
$('#add_row').hide();
}
});
$("#delete_row").click(function() {
if (i > 1) {
var r = confirm('Do you want to delete this item?');
if (r == true) {
$("#addr" + (i - 1)).html('');
i--;
$('#add_row').show();
}
} else {
alert("Entry cannot be deleted")
$('#delete_row').hide();
}
});
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<table class="table table-bordered table-hover" id="tab_add">
<tbody>
<tr>
<td colspan="2"><b>Customer Name</b></td>
<td colspan="1">
<select name="Per_Name[]" class="form-control">
<option value="">Select Customer</option>
<option value="2000001">John Doe</option>
<option value="2000002">Jane Doe</option>
<option value="2000003">Tom Harry</option>
<option value="2000004">Steve Jobs</option>
</select>
</td>
</tr>
<tr id='addr0'>
<td><b>1</b></td>
<td><b>Select Item</b></td>
<td colspan="1">
<select name="Sub_Name[]" class="form-control">
<option value="">Select Item</option>
<option value="1000001">Item A</option>
<option value="1000002">Item B</option>
<option value="1000003">Item C</option>
<option value="1000004">Item D</option>
</select>
</td>
<td><input type="text" name="itemPrice0" id="itemPrice0" class="itemPrice form-control" placeholder="Unit Price"></td>
<td><input type="number" name="Qty0" id="Qty0" class="Qty form-control" onkeypress="return isNumberKey(event)" placeholder="Quantity"></td>
<td><input type="text" name="linePrice0" id="linePrice0" class="linePrice form-control" onkeypress="return isNumberKey(event)" placeholder="Line Price" readonly></td>
<th>
<span class="glyphicon glyphicon-plus"></span>
<span class="glyphicon glyphicon-minus"></span>
</th>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
<table class="table table-bordered table-hover">
<tr id="finRow">
<td colspan="2" width="75%"><b>TOTAL</b></td>
<td><input type="text" name="priceTotal" id="priceTotal" class="row-total form-control" disabled></td>
</tr>
</table>
In order to reduce the amount of DOM traversal that you have to do to accomplish this, I suggest adding data-* attributes to your elements so that you can get the index and use that to reference the other elements directly.
<td><input type="text" name="itemPrice0" id="itemPrice0" data-index="0" class="itemPrice form-control" placeholder="Unit Price"></td>
<td><input type="number" name="Qty0" id="Qty0" data-index="0" class="Qty form-control" onkeypress="if(!isNumberKey(event)){return false;}" placeholder="Quantity"></td>
<td><input type="text" name="linePrice0" id="linePrice0" data-index="0" class="linePrice form-control" onkeypress="return isNumberKey(event)" placeholder="Line Price" readonly></td>
Then in your $("#add_row").click(function() { function we add data-index='"+j+"' when creating the new elements ...
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' data-index='"+j+"' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' data-index='"+j+"' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' data-index='"+j+"' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");
Finally, change your keyup handler to ...
$("#tab_add").on("keyup", ".Qty", function(e){
var qtyPur = parseFloat(this.value);
if (!isNaN(this.value) && this.value.length != 0) {
// this is where use use the data-index attribute to dynamically generate the target element ids
$("#linePrice"+$(this).data('index')).val(
parseFloat($("#itemPrice"+$(this).data('index')).val()) * qtyPur
);
}
calculateSum()
});
See Demo
This part of code will calculate linePrice of each row:
$("tr").each(function() {
if ($(this).children("td").length) {
$($($(this).children("td")[5]).children("input")[0]).val(
(($($($(this).children("td")[4]).children("input")[0]).val()) ? Number($($($(this).children("td")[4]).children("input")[0]).val()) : 0) *
(($($($(this).children("td")[3]).children("input")[0]).val()) ? Number($($($(this).children("td")[3]).children("input")[0]).val()) : 0)
)
}
});
function grosschanged_total1(a) {
var str = a;
var res = str.split("_");
//alert(res[2]);
var result = res[2];
var rate = parseFloat(document.getElementById("Gridview1_txtgross_" + result).value) * parseFloat(document.getElementById("Gridview1_txtrate_" + result).value);
var scale77 = 2;
// rate = roundNumberV2(rate, scale77);
var gresult = 0.00;
if(isNaN(rate)){
gresult= document.getElementById("Gridview1_txttotal_" + result).value = "";
} else{
gresult= document.getElementById("Gridview1_txttotal_" + result).value = parseFloat(Math.round(rate * 100) / 100).toFixed(2);
}
//GridView1_txtinvamt_0
var gfresult = parseFloat(gresult);
var ggresult = 0.00;
ggresult = gfresult + ggresult;
// $("[id*=lblGrandTotal]").html(ggresult);
//GridView1_txtdelinvnum_0 + GridView1_txtinvamt_0 = GridView1_txtgrosspt_0
// Calculate();
grosschanged_total1(a);
}
function Numerics(text) {
var regexp = /^[0-9]*$/;
if (text.value.search(regexp) == -1) {
text.value = text.value.substring(0, (text.value.length - 1));
alert('Numerics only allowed');
if (text.value.search(regexp) == -1)
text.value = "";
text.focus();
return false;
}
else
return true;
}
When the menu is selected from the radio buttons, and the amount of guests, the total price should be updated. But couldn't find the issue in the code. It is not updating.
When menu is clicked AND Amount of guests => Total Price update.
var proceed = 0;
var myTea = "";
var chosenTea;
function getSelectedText(selectList) {
return selectList.options[selectList.selectedIndex].text;
}
function getRadioValue(radioArray) {
var i;
for (i = 0; i < radioArray.length; i++) {
if (radioArray[i].checked)
return radioArray[i].value;
}
return "";
}
function getSelectedValue(selectList) {
return selectList[selectList.selectedIndex].value;
}
function view(form) {
var termsconds = form.terms.value;
var tea = getRadioValue(form.teaChoice);
var nb_people = getSelectedText(form.size);
var multiplier = parseInt(getSelectedValue(form.size));
var allergies = form.allergies.value;
var champagne = form.champ.value;
var champText = "";
var special;
if (champagne = true) {
special = 10;
champText = "with champagne";
} else {
special = 0;
champText = "";
}
var teaprice;
if (tea !== null) {
teaprice = parseInt(tea)
} else {
teaprice = 0;
}
var totalprice;
var additional;
var totalOrder;
totalprice = (teaprice + special) * multiplier;
if (allergies !== null) {
additional = "allergies to: " + allergies;
} else {
additional = " no food allergy ";
}
form.price.value = totalprice;
if (proceed === 1) {
if (termsconds === false) {
alert("you must read the terms and conditions");
} else {
if (myTea === null) {
alert("You must choose tea before you can proceed with order");
proceed = 0;
} else {
totalOrder = "you have ordered a " + chosenTea + champText + "for " + nb_people + " and we have" +
"noted that you have " + additional + ".\nYour toal bill is \u00A3" + totalprice + ".\n";
confirm(totalOrder);
proceed = 0;
}
}
}
}
function displayTea(teaName) {
myTea = document.getElementById("chosenTea");
myTea.value = teaName;
chosenTea = teaName;
}
body {
color: #FFFFFF;
}
h1 {
font-family: "corsoiva", serif;
color: #005080;
font-size: 40px;
}
#myTable {
background-color: #50a0d0;
}
.myBlue {
color: #005080;
}
.myWhite {
background-color: #FFFFFF;
}
.toRight {
float: right;
text-align: right;
}
<center>
<h1>Welcome to Web Tech's Afternoon tea</h1>
<form>
<table border="5" cellpadding="10" cellspacing="5" id="myTable">
<tr>
<td colspan="2" align="center">
<h2>Please chosse from the menu below <br> and select the number of people </h2>
</td>
</tr>
<tr>
<td colspan="2" class="myWhite">
<span class="myBlue">Please select your menu:</span><br>
<input type="radio" name="teaChoice" value="20" onclick="displayTea('Easter AFternoon Tea');view(this.form)">
<input type="radio" name="teaChoice" value="30" onclick="displayTea('Pastries and specialist');view(this.form)">
<input type="radio" name="teaChoice" value="15" onclick="displayTea('Traditional Afternoon Tea');view(this.form)">
<br>
<span class="myBlue">Your tea: </span>
<input type="text" id="chosenTea" size="50">
</td>
</tr>
<tr>
<td colspan="2">
<div align="left">Please select party size and champagne option: <br><br>
<select name="size" onclick="view(this.form)">
<option value="1">1 guest </option>
<option value="2">2 guest </option>
<option value="3">3 guest </option>
<option value="4">4 guest </option>
</select>
<input type="checkbox" name="champ" value="champagne" onclick="view(this.form)">with champagne</div>
<div class="toRight">Please enter food allergies in the input field below: <br>
<input type="text" name="allergies" size="60"></div>
</td>
</tr>
<tr>
<td><b>Total price:$</b><input type="text" name="price" size="4"></td>
<td rowspan="2" align="center"><br><br>
<input type="button" name="proceedOrder" value="Proceed with order" onclick="view(this.form);return view(this.form)">
</td>
</tr>
<tr>
<td><input type="checkbox" name="terms " value="read"> I have read and accepted the <a href="Terms.html">terms and
conditions</a>
</td>
</tr>
</table>
</form>
</center>
There is a space in your HTML at name="terms ": remove it. Then form.terms will be valid in your code.
You could have spotted this if you would have checked the console for errors, as in your current version the following line:
var termsconds = form.terms.value;
... produces:
form.terms is undefined
I am working with jQuery table with some calculations and with results it gave me some warning messages and i want that if there is any warning message of right side of any row of the table then it should just show me the value "BULK" below table under id="result" and that should not reflect with another values of table.
here is the site link : http://sea.studioscue.in/test.php
<script type="text/javascript">
$(function () {
$('.pnm, .price, .subtot, .widtot, .perm, .tottot, .vol, .tot, .vols, .heights, .acts, .heitot').prop('readonly', true);
var $tblrows = $("#tblProducts tbody tr");
$tblrows.each(function (index) {
var $tblrow = $(this);
$tblrow.find('.width, .height, .carton, .perm, .act').on('change', function () {
var carton = $tblrow.find("[name=carton][type=number][min=0]").val();
var height = $tblrow.find("[name=height][type=number][min=0]").val();
var width = $tblrow.find("[name=width][type=number][min=0]").val();
var act = $tblrow.find("[name=act][type=number][min=0]").val();
var perm = $tblrow.find("[name=perm]").val();
var subTotal = parseFloat(height*0.01, 10) * parseInt(carton, 10);
var cartons =parseInt(carton, 10);
if (!isNaN(cartons)) {
$tblrow.find('.carton').val(cartons.toFixed(0));
var cartonTotal = 0;
$(".carton").each(function () {
var stval = parseInt($(this).val());
cartonTotal += isNaN(stval) ? 0 : stval;
});
$('.cartontot').val(cartonTotal.toFixed(0));
}
if (!isNaN(subTotal)) {
$tblrow.find('.perm').val(subTotal.toFixed(5));
var grandTotal = 0;
$(".perm").each(function () {
var stval = parseFloat($(this).val());
grandTotal += isNaN(stval) ? 0 : stval;
});
$('.grdtot').val(grandTotal.toFixed(5));
}
$('.grdtot').val(grandTotal.toFixed(5));
var length = $(this).val();
var lngthOnly = ($(this).attr('class') == 'length') ? length : false;
var width = $(this).val();
var wdthOnly = ($(this).attr('class') == 'width') ? width : false;
var height = $(this).val();
var hightOnly = ($(this).attr('class') == 'height') ? height : false;
var carton = $(this).val();
var cartonOnly = ($(this).attr('class') == 'carton') ? carton : false;
var act = $(this).val();
var actOnly = ($(this).attr('class') == 'act') ? act : false;
if (grandTotal > 7 && lngthOnly < 590 && lngthOnly < 1201 && wdthOnly < 235 && hightOnly < 238 && hightOnly < 269) {
$('#result').html('FCL');
} else if (grandTotal < 7 && lngthOnly < 590 && lngthOnly < 1201 && wdthOnly < 235 && hightOnly < 238 && hightOnly < 269) {
$('#result').html('LCL');
}
else if ((grandTotal < 7 || grandTotal > 7) && (lngthOnly > 590 || lngthOnly > 1201 || wdthOnly > 235 || hightOnly > 238))
{
$('#result').html('BULK');
}
var height = $(this).val();
var hightOnly = ($(this).attr('class') == 'height') ? height : false;
var subCalc = parseFloat(height);
if (!isNaN(subCalc)) {
$tblrow.find('.calcheight').val(subCalc.toFixed(5));
var calcTotal = 0;
$(".calcheight").each(function () {
var stval = parseFloat($(this).val());
calcTotal += isNaN(stval) ? 0 : stval;
});
$('.heitot').val(calcTotal.toFixed(5));
}
var sp = subCalc;
hightOnly = parseFloat(hightOnly);
if(hightOnly > 238 && hightOnly < 269) {
$(this).closest('tr').find('td.error').text("Cargo won't fit in 20STD and 40STD Containers, change the mode to bulk");
} else if(hightOnly > 269){
$(this).closest('tr').find('td.error').text("Cargo won't fit in 20STD, 40STD and 40HC Containers, change the mode to bulk");
} else if(hightOnly < 269) {
$(this).closest('tr').find('td.error').text('');
}
var width = $(this).val();
var wdthOnly = ($(this).attr('class') == 'width') ? width : false;
var subCalcwidth = parseFloat(width);
if (!isNaN(subCalcwidth)) {
$tblrow.find('.calcwidth').val(subCalcwidth.toFixed(5));
var calcwidthTotal = 0;
$(".calcwidth").each(function () {
var stval = parseFloat($(this).val());
calcwidthTotal += isNaN(stval) ? 0 : stval;
});
$('.widtot').val(calcwidthTotal.toFixed(5));
}
var spwidth = subCalcwidth;
wdthOnly = parseFloat(wdthOnly);
if (wdthOnly > 235) {
$(this).closest('tr').find('td.errorwidth').text("Cargo won't fit in 20STD, 40STD and 40HC Containers, change the mode to bulk");
} else if (wdthOnly < 235) {
$(this).closest('tr').find('td.errorwidth').text('');
}
});
});
});
</script>
<table id="tblProducts">
<thead>
<tr>
<td><strong>Packages</strong></td>
<td><strong>Cartons</strong></td>
<td><strong>Cm Width</strong></td>
<td><strong>Cm Height</strong></td>
<td><strong>Act Kilos</strong></td>
<td><strong>M3</strong></td>
<td><strong>Warning Messages</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="pnm" value="Product One" name="pnm" style="width:120px" /></td>
<td ><input type="number" oninput="validity.valid||(value='');" class="carton" value="0" name="carton" min="0" maxlength="5" style="width:70px"></td>
<td><input type="number" onKeyPress="return AllowOnlyNumbers(event);" oninput="validity.valid||(value='');" class="width" value="0" min="0" name="width" maxlength="5" style="width:110px"/></td>
<td><input type="number" oninput="validity.valid||(value='');" class="height" value="0" min="0" name="height" maxlength="5" style="width:110px"/></td>
<td><input type="number" onKeyPress="return AllowOnlyNumbers(event);" oninput="validity.valid||(value='');" class="act" value="0" min="0" name="act" maxlength="5" style="width:90px"/></td>
<td><input type="number" class="perm" value="" name="perm" style="width:80px"/></td>
<td class="error" style="color:red"></td> <td class="errorwidth" style="color:red"></td>
</tr>
<tr>
<td><input type="text" class="pnm" value="Product Second" name="pnm" style="width:120px" /></td>
<td ><input type="number" oninput="validity.valid||(value='');" class="carton" value="0" name="carton" min="0" maxlength="5" style="width:70px"></td>
<td><input type="number" onKeyPress="return AllowOnlyNumbers(event);" oninput="validity.valid||(value='');" class="width" value="0" min="0" name="width" maxlength="5" style="width:110px"/></td>
<td><input type="number" oninput="validity.valid||(value='');" class="height" value="0" min="0" name="height" maxlength="5" style="width:110px"/></td>
<td><input type="number" onKeyPress="return AllowOnlyNumbers(event);" oninput="validity.valid||(value='');" class="act" value="0" min="0" name="act" maxlength="5" style="width:90px"/></td>
<td><input type="number" class="perm" value="" name="perm" style="width:80px"/></td>
<td class="error" style="color:red"></td><td class="errorwidth" style="color:red"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td><input type="number" class="cartontot" value="" name="" style="width:70px" readonly/></td>
<td></td>
<td></td>
<td></td>
<td><input type="number" class="grdtot" value="" name="" style="width:80px" readonly/></td>
</tr>
</tfoot>
Regards
Ankit
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>