I have this Javascript function that the discount applies to either FlavorBlue or FlavorRed. I tried to add the quantities together, but it did not work as expected. The goal was to have a 50% for quantity 2 flavors either blue or red. I have searched this site for help until blue and red in the face... Any insight would be extremely valued. Thanks in advance.
.js file:
function ordertotals()
{
var FlavorBluetotal = (order.selectFlavorBlueQuantity.value *
FlavorBlueprice.value);
document.getElementById('FlavorBluetotal').innerHTML = FlavorBluetotal;
order.FlavorBluetotalvalue.value = FlavorBluetotal;
var FlavorRedtotal = (order.selectFlavorRedQuantity.value *
FlavorRedprice.value);
document.getElementById('FlavorRedtotal').innerHTML = FlavorRedtotal;
order.FlavorRedtotalvalue.value = FlavorRedtotal;
var FlavorBluecasetotal = (order.selectFlavorBlueCaseQuantity.value *
FlavorBluecaseprice.value);
document.getElementById('FlavorBluecasetotal').innerHTML =
FlavorBluecasetotal;
order.FlavorBluecasetotalvalue.value = FlavorBluecasetotal;
// var total = FlavorBluetotal + FlavorRedtotal + FlavorBluecasetotal;
// document.getElementById('ordertotal').innerHTML = total;
// order.ordertotalvalue.value = total;
var totala = 0;
var totalb = 0;
var totalc = 0;
var quantity = (order.selectFlavorBlueQuantity.value +
order.selectFlavorRedQuantity.value);
// document.getElementById("insert").innerHTML = quantity;
if (order.selectFlavorBlueQuantity.value > 1) {
quantitya = (order.selectFlavorBlueQuantity.value);
var price = 29;
if (quantitya % 2 == 0) {
//calculate here buy one get one half price
real = ((quantitya/2)*price);
half = ((quantitya/2)*(price/2));
totala = (real+half);
} else {
quantitya = (quantitya-1);
real = ((quantitya/2)*price);
half = ((quantitya/2)*price/2);
totala = (real+half+price);
}
} else {
if (order.selectFlavorRedQuantity.value > 1) {
quantityc = (order.selectFlavorRedQuantity.value);
var price = 29;
if (quantityc % 2 == 0) {
//calculate here buy one get one half price
real = ((quantityc/2)*price);
half = ((quantityc/2)*(price/2));
totalc = (real+half);
} else {
quantityc = (quantityc-1);
real = ((quantityc/2)*price);
half = ((quantityc/2)*price/2);
totalc = (real+half+price);
}
}
}
if (order.selectFlavorBlueQuantity.value == 1 &&
order.selectFlavorRedQuantity.value == 1) {
var quantityb = 2;
var price = 29;
if (quantityb % 2 == 0) {
//calculate here buy one get one half price
real = ((quantityb/2)*price);
half = ((quantityb/2)*(price/2));
totalb = (real+half);
} else {
quantityb = (quantityb-1);
real = ((quantityb/2)*price);
half = ((quantityb/2)*price/2);
totalb = (real+half+price);
}
}
// if (order.selectFlavorBlueQuantity.value == 1 ||
order.selectFlavorRedQuantity.value == 1) {
// var quantityd = 1;
// var price = 29;
// totald = (quantityd * price);
// } else {
// }
// total = (totala + totalb + totalc + totald + FlavorBluecasetotal);
total = (totala + totalb + totalc + FlavorBluecasetotal);
document.getElementById('ordertotal').innerHTML = total;
order.ordertotalvalue.value = total;
}
php file:
//Inventory
echo "<tr><td colspan='2'><u>Select Inventory:</u></td></tr>";
//Quantity Flavor Blue
echo "<tr><td>Quantity of Flavor Blue:</td><td>";
echo "<label>$</label><input type='text' id='FlavorBlueprice'
name='FlavorBlueprice' maxlength='4' value='$FlavorBlueprice'
style='width:20px;'> <label>X</label> ";
echo "<input type='text' id='selectFlavorBlueQuantity'
name='selectFlavorBlueQuantity' maxlength='4'
value='$selectFlavorBlueQuantity' onchange='ordertotals();'
style='width:20px;'>";
echo "</select><label id='asterisk'> *</label>";
echo " <label>=</label> <label>$</label><label
id='FlavorBluetotal'></label>";
echo "</td></tr>";
//Quantity Flavor Red
echo "<tr><td>Quantity of Flavor Red:</td><td>";
echo "<label>$</label><input type='text' id='FlavorRedprice'
name='FlavorRedprice' maxlength='10' value='$FlavorRedprice'
style='width:20px;'> <label>X</label> ";
echo "<input type='text' id='selectFlavorRedQuantity'
name='selectFlavorRedQuantity' maxlength='4'
value='$selectFlavorRedQuantity' onchange='ordertotals();'
style='width:20px;'>";
echo "</select><label id='asterisk'> *</label>";
echo " <label>=</label> <label>$</label><label
id='FlavorRedtotal'></label>";
echo "</td></tr>";
//Quantity Flavor Blue
echo "<tr><td>Quantity of Flavor Blue Case:</td><td>";
echo "<label>$</label><input type='text' id='FlavorBluecaseprice'
name='FlavorBluecaseprice' maxlength='10' value='$FlavorBluecaseprice'
style='width:20px;'> <label>X</label> ";
echo "<input type='text' id='selectFlavorBlueCaseQuantity'
name='selectFlavorBlueCaseQuantity' maxlength='4'
value='$selectFlavorBlueCaseQuantity' onchange='ordertotals();'
style='width:20px;'>";
echo "</select><label id='asterisk'> *</label>";
echo " <label>=</label> <label>$</label><label
id='FlavorBluecasetotal'></label>";
echo "</td></tr>";
//Total
echo "<tr><td>Total:</td><td><label>$</label><label id='ordertotal'></td>
</tr>";
echo "<tr><td colspan='2'><hr></td></tr>";
I was just mistakenly had if else nested inside another. simple fix.
Related
Problem is I cannot click the Tabs on the website and If i click on Tabs; it show
Uncaught Type Error: Cannot set properties of null (setting 'value').
Is there any way to fix this? Also, I am a beginner and I don't know how to fix this. Codes are written in PHP and Javascript.
<?php
// session_start();
require("checklogin.php");
$toolsname = "Matrix Setup";
$toolsnamepath = "index.php";
$userlogin = $loginname;
$usrgroup = $_SESSION["usrgrp"];
$str_tab = isset($_POST["str_tab"])? $_POST["str_tab"] : "";
$winwidth = isset($_POST["winwidth"])? $_POST["winwidth"] : "";
$ch = isset($_POST["ch"])? $_POST["ch"] : "";
$badgeno = isset($_SESSION["badgeno"])? $_SESSION["badgeno"] : "";
if($str_tab == ""){
$str_tab = isset($_GET["str_tab"])? $_GET["str_tab"] : "";
}
if($winwidth == ""){
$winwidth = isset($_GET["winwidth"])? $_GET["winwidth"] : "";
}
if($ch == ""){
$ch = isset($_GET["ch"])? $_GET["ch"] : "";
}
echo "<html>";
echo "<head><title>$toolsname</title>";
echo "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=5\">";
echo "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"\web/css/lotmgt_edge.css\"/>";
echo "<script src=\"lotmgt.js\"></script>\n";
echo "<script src=\"setup/setup.js\"></script>\n";
echo "<script src=\"productmatrix/productmatrix.js\"></script>\n";
echo "<script src=\"simulator/simulator.js\"></script>\n";
echo "<script src=\"addmatrix/addmatrix.js\"></script>\n";
echo "<script src=\"addAVImatrix/addmatrix.js\"></script>\n";
echo "<script src=\"\web/js/eregister/pointer.js\" type=\"text/javascript\"></script>";
echo "</head>";
echo "<body onload=OnLoad('" . $ch . "','" . $badgeno . "')>";
//include($_SERVER['DOCUMENT_ROOT']."\library\common\apewsheader.php");
//include($_SERVER['DOCUMENT_ROOT']."\library\common\db_config.inc");
//include($_SERVER['DOCUMENT_ROOT']."\library\common\standard_defines.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/apewsheader.php");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/db_config.inc");
include("//sgewsnant21.amk.st.com/ewsweb/wwwroot/library/common7/standard_defines.inc");
include("editme.php");
echo "<form name=\"lotmgt\" method=\"post\" target=\"_self\" onsubmit=\"return false;\">";
echo "<div style=\"position:relative; top:20px;\">";
echo "<table cellpadding=\"3\" cellspacing=\"0\" border=\"0\" width=\"99%\">";
echo "<tr>";
echo "<td>";
for($c=0;$c<count($ary_tab);$c++) {
$class_tab = (($ch=="ProductMatrix" && $ary_tab[$c]=="Product Matrix" && (!isset($str_tab) || $tr_tab=="")) || ($ch=="SocketSimulator" && $ary_tab[$c]=="Socket Simulator" && (!isset($str_tab) || $str_tab=="")) || ($ch=="AVIMatrixAdd" && $ary_tab[$c]=="AVI Matrix Add" && (!isset($str_tab) || $str_tab=="")) || ($ch=="SetupPostTest" && $ary_tab[$c]=="Setup PostTest" && (!isset($str_tab) || $str_tab=="")) || ($ch=="Setup" && $ary_tab[$c]=="Setup" && (!isset($str_tab) || $str_tab=="")) || (($c==0 && !isset($str_tab)) && $ch=="") || $ary_tab[$c] == $str_tab)? "link_tab_slct" : "link_tab";
echo "" . $ary_tab[$c] . "";
}
echo"</td>";
echo"</tr>";
echo"</table>";
echo "</div>";
//echo $str_tab;
if($str_tab != ""){
switch($str_tab){
case "Setup":
include("setup/setup.php");
break;
case "Setup PostTest":
include("setup/setup.php");
break;
case "Setup1":
include("setup1/setup.php");
break;
case "Product Matrix":
include("productmatrix/productmatrix.php");
break;
case "Socket Simulator":
// include("simulator/simulator.php");
include("simulator/Socket_simulator.php");
break;
// case "Matrix Add":
// include("addmatrix/addmatrix.php");
// break;
case "AVI Matrix Add":
include("addAVImatrix/addmatrix.php");
break;
}
}
else {
if ($ch=="ProductMatrix") {
include("productmatrix/productmatrix.php");
}
else if($ch=="SocketSimulator"){
// include("simulator/simulator.php");
include("simulator/Socket_simulator.php");
}
else if($ch=="AVIMatrixAdd"){
include("addAVImatrix/addmatrix.php");
}
else if($ch=="Setup"){
include("setup/setup.php");
}
else if($ch=="SetupPost6E"){
include("setup/setup.php");
}
else{
include("setup/setup.php");
}
}
//common
echo "<input type=\"hidden\" name=\"str_tab\" value=\"" . $str_tab . "\">";
echo "<input type=\"hidden\" name=\"winwidth\" value=\"" . $winwidth . "\">";
echo "<input type=\"hidden\" name=\"username\" value=\"" . $loginname . "\">";
echo "</form>";
flush();
mysqli_close($conn);
echo "</body>";
echo "</html>";
?>
Above codes are index.php codes.
var winplanproducttoentity = '';
var winupdateauto = '';
var winupdatebytester = '';
var winupdatebyproduct = '';
var winupdatestatus = '';
var wintestlot = '';
var winassignlot = '';
var winshowlot = ''
var winchecksicom = '';
var w;
var winwidth = window.screen.width;
var div = new Array('outputdiv','setupdiv');
//var div = new Array('outputdiv','setupdiv','availdiv');
var reqHttp = InitRequest();
var reqHttp1 = InitRequest();
var reqHttp2 = InitRequest();
var reqHttp3 = InitRequest();
function InitRequest() {
var request=null;
try {
request=new XMLHttpRequest();
}
catch (e) {
try {
request=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return request;
}
function AsynReqData(request,url,fn) {
request.open("GET", url + '&sid=' + Date() + Math.random(), true);
request.onreadystatechange = eval(fn);
request.send(null);
}
function SynReqData(request,url) {
request.open("GET", url + '&sid=' + Date() + Math.random(), false);
request.send(null);
return request.responseText;
}
function DisplayTab(tabname,tabid) {
document.getElementById(tabid).value = tabname; // this is the $str_tab
document.lotmgt.submit();
}
function OnLoad(ch,badgeno){
var tab = document.lotmgt.str_tab.value; // this is the $str_tab from DisplayTab function
w = (winwidth < 1280)? 1280 : winwidth;
if((tab=='' & ch=='') || tab=='Setup' || (ch=='Setup' & tab=='')) {
var p_1 = "checked";
var T_0 = "checked";
var zmiss = "checked";
for(var i=0; i<div.length; i++) {
document.getElementById(div[i]).className = 'hide';
}
// var wd = (128*5) - 10;
var wd = (128*7.5) - 50;
var lf = 0;
document.getElementById('filterdiv').style.width = wd + 'px';
document.getElementById('filterdiv').style.left = lf + 'px';
wd = (128*5.5) - 80;
lf = (128*5) - 10; // lf = (128*7) - 20;
document.getElementById('waferdiv').style.width = wd + 'px';
document.getElementById('waferdiv').style.left = lf + 'px';
// AsynReqData(reqHttp,'setup/content_wafer.php?site=','UpdateWafer');
AsynReqData(reqHttp1,'setup/content_filter.php?site=' + '' + '&badgeno=' + badgeno + '&p_1=' + p_1 + '&T_0=' + T_0 + '&zmiss=' + zmiss,'UpdateFilter');
}
else if (tab=='Product Matrix' || (ch=='ProductMatrix' & tab=='')){
AsynReqData(reqHttp,'productmatrix/content_filter.php?area=','UpdatePMFilter');
}
// else if (tab=='Matrix Simulator' || (ch=='MatrixSimulator' & tab=='')){
// // AsynReqData(reqHttp,'simulator/content_filter.php?area=','UpdateSIMFilter');
// }
else if (tab=='Setup PostTest' || (ch=='SetupPostTest' & tab=='')){
var p_1 = "checked";
var T_0 = "checked";
var wd = (128*9) - 50;
var lf = 0;
document.getElementById('filterdiv').style.width = wd + 'px';
document.getElementById('filterdiv').style.left = lf + 'px';
AsynReqData(reqHttp1,'setup/content_filter1.php?site=' + '' + '&badgeno=' + badgeno + '&p_1=' + p_1 + '&T_0=' + T_0,'UpdateFilter');
}
}
//shared functions
function ManagePopup(except){
var mywin = new Array('winplanproducttoentity','winupdateauto','winupdatebytester','winupdatebyproduct','winupdatestatus','wintestlot','winassignlot','winshowlot','winchecksicom');
for(var i=0; i<mywin.length; i++) {
var win = window[mywin[i]];
if (mywin[i] == except){
if(!win.closed && win.location) win.focus();
}
else{
if(!win.closed && win.location) win.close();
}
}
}
function PlanProductToEntity(product,type){
var w = 300;
var h = 600;
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
var winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no';
ManagePopup('winplanproducttoentity');
winplanproducttoentity = this.open('../lotmgt/wip/pop_assignproduct.php?product=' + product + '&type=' + type, 'winplanproducttoentity', winprops);
}
Above codes are Javascript codes. Error says in Javascript and How to fix that?
The error occurs in the JS code and is due to the HTML generated in PHP which is missing an id attribute.
You seem to get the error here: document.getElementById(tabid).value = tabname; because document.getElementById(tabid) is null.
When it looks for the element with id str_tab it doesn't find it. The only element in the HTML which could be the desired one has the attribute name="str_tab" and it's your hidden field. You have to add the missing id="str_tab" attribute to this hidden field.
I'm new to both Progress and JavaScript. I'm getting elements from a temp-table in Progress using json. I'll show part of my code.
$.post({
url: gWS + "/bass/bass054.p",
data: {
"process": "<?php echo $process; ?>"
},
success: function(data){
var table = document.getElementById("table");
var j = 0;
var dataProc = "";
var qtProc = 0;
var item = "";
var sumQt = 0;
var qt_total = 0;
var idGrp = "";
for (var i = 0; i < data["tt-base"].length; i++) {
var row = table.insertRow(j+2);
if (data["tt-base"][i]["cod_id_bloco_edi"] != idGrp && i>=2) {
if (sumQt == qt_total) {
row.style.background = "green";
} else {
row.style.background = "#ff0000";
}
row.insertCell(0).innerHTML = "<b>QT TOTAL:</b>";
row.insertCell(1).innerHTML = "<b>" + item + "</b>";
row.insertCell(2).innerHTML = "<b>" + sumQt + "</b>";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<b>" + qt_total + "</b>";
sumQt = 0;
j++;
row = table.insertRow(j+2);
}
if (data["tt-base"][i]["cdn_segment_edi"] == 44) {
row.style.background = "#00ff00";
dataProc = data["tt-base"][i]["dsl_dados_entr_edi"].substring(7,9) + "/" + data["tt-base"][i]["dsl_dados_entr_edi"].substring(5,7) + "/20" + data["tt-base"][i]["dsl_dados_entr_edi"].substring(3,5) + "</div>";
qtProc = parseInt(data["tt-base"][i]["dsl_dados_entr_edi"].substring(11,20), 10) + "</div>";
row.insertCell(0).innerHTML = dataProc;
row.insertCell(1).innerHTML = qtProc;
row.insertCell(2).innerHTML = " ";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<div class='p6'> </div>";
j++;
sumQt = parseInt(sumQt,10) + parseInt(qtProc,10);
} else if (data["tt-base"][i]["cdn_segment_edi"] == 446) {
if (data["tt-base"][i]["dsl_dados_entr_edi"].indexOf("PRE") == 10) {
document.getElementById("table").deleteRow(j+1);
j--;
row = table.insertRow(j+2);
row.style.background = "#0099CC";
row.insertCell(0).innerHTML = dataProc;
row.insertCell(1).innerHTML = qtProc;
row.insertCell(2).innerHTML = "PREVIS";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<div class='p6'> </div>";
dataProc = '';
qtProc = 0;
j++;
} else if (data["tt-base"][i]["dsl_dados_entr_edi"].indexOf("FIR") == 10) {
document.getElementById("table").deleteRow(j+1);
j--;
row = table.insertRow(j+2);
row.style.background = "#00ff00";
row.insertCell(0).innerHTML = dataProc;
row.insertCell(1).innerHTML = qtProc;
row.insertCell(2).innerHTML = "FIRM";
row.insertCell(3).colSpan = "2";
row.insertCell(4).innerHTML = "<div class='p6'> </div>";
dataProc = '';
qtProc = 0;
j++;
}
}
idGrp = data["tt-base"][i]["cod_id_bloco_edi"];
}
}
}).fail(function() {
alert("Not Possible.");
})
So, instead of deleting the row as I'm doing it now I'd like to replace the previous only the cells with the FIRM and PREVIS. I tried using only row.insertCell(2).innerHTML = "PREVIS"; but it didn't work correctly.
Is there any suggestion as to how can I do it? Sorry if I'm not clear enough as i'm new to all this. Thanks for your time.
I managed to do what I wanted after tweaking for hours, lol.
Instead of using insertRow or insertCell, I just used the following
table.rows[j+2].style.background = "#0099CC";
table.rows[j+2].cells[2].innerHTML = "PREVIS";
This way, I was able to replace the content of what I wanted. I still have to change some other details, but the most difficult part is finally gone. Sorry if I wasted your time, but writing here has helped me to see the code in a different angle. I hope my code can help other people.
I want to change the value of initialValue after each run Ex: If I type 1000, this will give the output as 11,000 (10000 + 1,000), and I minus and I type 2000, this will give the output as 9,000 (11,000 - 2,000). Can somebody help me regarding to my problem.
function Compute(initialNum, numOne) {
this._initialNum = 10000;
this._numOne = numOne;
this.addNum = function() {
this._initialNum = +this._initialNum + +this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum = +this._initialNum - +this._numOne;
return this._initialNum;
};
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="hidden" id="persistedResult" value="10000" /><br><br>
<input type="radio" id="rdoAdd" name="rdo">Add<br><br>
<input type="radio" id="rdoMinus" name="rdo">Minus<br><br>
<input type="text" id="txtNumOne"><br><br>
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
<script src="java.js"></script>
<script>
var tblResult = document.getElementById("tblResult");
var personList = [];
function printResult() {
var display = "";
var initialValue = parseInt(document.getElementById("persistedResult").value);
//var objAccount = new Compute(initialValue, numOne);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
//var numTwo = parseInt(document.getElementById('txtNumTwo').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
var newValue = 0;
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
//display += objAccount.addNum();
newValue = personList[i].addNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
//display += objAccount.minusNum();
newValue = personList[i]. minusNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
document.getElementById("persistedResult").value = newValue;
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
</script>
</body>
</html>
I want to change the value of initialValue after each run Ex: If I type 1000, this will give the output as 11,000 (10000 + 1,000), and I minus and I type 2000, this will give the output as 9,000 (11,000 - 2,000). Can somebody help me regarding to my problem.
//constructor function
function Compute(initialNum, numOne) {
this._initialNum = 10000;
this._numOne = numOne;
this.addNum = function() {
this._initialNum = +this._initialNum + +this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum = +this._initialNum - +this._numOne;
return this._initialNum;
};
}
//javascript in the body tag
var tblResult = document.getElementById("tblResult");
var personList = [];
function printResult() {
var display = "";
var initialValue = parseInt(document.getElementById("persistedResult").value);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
var newValue = 0;
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
newValue = personList[i].addNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
newValue = personList[i]. minusNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
document.getElementById("persistedResult").value = newValue;
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input type="hidden" id="persistedResult" value="10000" /><br><br>
<input type="radio" id="rdoAdd" name="rdo">Add<br><br> //rdo for Add
<input type="radio" id="rdoMinus" name="rdo">Minus<br><br> //rdo for Subs
<input type="text" id="txtNumOne"><br><br>
<button onclick="printResult()">Compute</button><br><br>
<table border="1px">
<th>Result</th>
<tbody id = "tblResult">
</tbody>
</table>
</body>
</html>
I want to change the value of initialValue after each run Ex: If I type 1000, this will give the output as 11,000 (10000 + 1,000), and I minus and I type 2000, this will give the output as 9,000 (11,000 - 2,000). Can somebody help me regarding to my problem.
function printResult() {
var display = "";
var initialValue = 10000;
//var objAccount = new Compute(initialValue, numOne);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
//var numTwo = parseInt(document.getElementById('txtNumTwo').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
//display += objAccount.addNum();
display = "<tr>";
display += "<td>" + (personList[i].addNum()) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
//display += objAccount.minusNum();
display = "<tr>";
display += "<td>" + (personList[i].minusNum()) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
}
//Constructor Function
function Compute(initialNum, numOne) {
this._initialNum = initialNum;
this._numOne = numOne;
this.addNum = function() {
this._initialNum += this._numOne;
return this._initialNum;
};
this.minusNum = function() {
this._initialNum -= this._numOne;
return this._initialNum;
};
}
Since HTTP is stateless and you want to perform operations on 2 different actions, you will need to store the result of each action in some place. For the simplest example, you can create hidden field on your HTML page. This can have value of 10000 when your HTML is loaded for the first time and update it’s value after each action is executed.
Let’s assume you have following hidden field on your HTML:
<input type=“hidden” id=“persistedResult” value=“10000” />
Here is your updated printResult method:
function printResult() {
var display = "";
var initialValue = parseInt(document.getElementById(‘persistedResult’).value);
//var objAccount = new Compute(initialValue, numOne);
var rdoAdd = document.getElementById("rdoAdd");
var rdoMinus = document.getElementById("rdoMinus");
var numOne = parseInt(document.getElementById('txtNumOne').value);
//var numTwo = parseInt(document.getElementById('txtNumTwo').value);
var objCompute = new Compute(initialValue, numOne);
personList.push(objCompute);
console.log(personList);
var newValue = 0;
for(var i = 0; i < personList.length; i++) {
if(rdoAdd.checked) {
//display += objAccount.addNum();
newValue = personList[i].addNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
} else if(rdoMinus.checked){
//display += objAccount.minusNum();
newValue = personList[i]. minusNum();
display = "<tr>";
display += "<td>" + (newValue) + "</td>";
display += "<tr>";
tblResult.innerHTML += display;
resetx();
}
}
document.getElementById(‘persistedResult’).value = newValue;
}
Note: This is a primitive example to guide you how to achieve data persistence. Generally, the data will be persisted on server.
This code takes care of scenario where there is only one person in the list, which is the approach in your current code example. You will need to enhance the logic if you want to have this working on an array of persons.
var valueEl = document.getElementById('value');
var addEl = document.getElementById('add');
var resultEl = document.getElementById('result');
var calculateEl = document.getElementById('calculate');
var initialValue = 1000;
function appendResult(result) {
var liEl = document.createElement("li");
liEl.innerHTML = result;
resultEl.appendChild(liEl);
}
function handleClickCalculate() {
var operand = addEl.checked ? 1 : -1;
var value = +valueEl.value * operand;
initialValue += value
appendResult(initialValue);
}
calculateEl.addEventListener('click', handleClickCalculate)
appendResult(initialValue);
jsFiddle
This code works perfect for Items that have the same address.
If they have same addressId, then they are grouped together under that one address.
5 items same address that shows up fine, but it is placing the same shipping fee for each item.
Need to only show the same as address, only one shipping fee for Same Group of items.
Please help, I have been trying at this for past two-days..Cannot figure out how to return the one shipping fee for group of items.
var itemshippingGroup, should be grouped shipping fee, display, only one of those fees, not each 5-items as separate fee.
See code below
//cart rows
var numofItems = productCart.length;
var productSubTotal = 0, shipping = 0;
var retriveAdd = getStoredData(address_cookie_name);
//alert(retriveAdd);
var productAddress = $.parseJSON(retriveAdd);
var k = 0;
for(var ad in productAddress){
var j = 0;
for(var i in productCart) {
var ship = 0;
var value = productCart[i];
var addressId = productCart[i].addressId;
var shippingId = parseFloat(productCart[i].shippingmethod).toFixed(2);
if(ad == addressId){
var item = parseInt(i)+1;
var address = productAddress[productCart[i].addressId];
var itemshipping = parseFloat(productCart[i].shippingmethod).toFixed(2);
var fName = '', lName = '';
if(address){
fName = address.firstName;
lName = address.lastName;
itemAddress = address.address1+" <br> "+ address.city+","+address.state+" "+address.zipcode;
if(addressId == shippingId){
var itemshippingGroup = shippingId;
}
}
// Sub Total
productSubTotal = productSubTotal + ((parseFloat(value.productPrice) + parseFloat(value.productTax)) * value.productQty);
var trStyle = "style='background-color:#FFFFFF;'";
if(k%2 == 0){
trStyle = "style='background-color:#F1F1F1;'";
}
cart_html += '<tr id="cart_row_'+i+'" class="cart_row" '+trStyle+'>';
cart_html += '<td class="confirm-product"><span class="clearfix first_item last_item"><img src="'+value.productImage+'" alt="" title="'+value.productName+'" class="cart-images"></td>';
cart_html += '<td>'+value.productName+'<br>'+fName+' '+lName+'</td>';
if(j == 0){
cart_html += '<td>'+itemAddress+'</td>';
}else{
cart_html += '<td> </td>';
}
j++;
cart_html += '<td>'+currencySymbol+''+parseFloat(value.productPrice).toFixed(2)+'</td>';
cart_html += '<td>'+currencySymbol+''+parseFloat(value.productTax)+'</td>';
cart_html += '<td class="itemshipping">'+currencySymbol+' '+itemshipping+'</td>';
//cart_html += '<td>'+currencySymbol+' '+itemshipping+'</td>';
cart_html += '<td>'+currencySymbol+' '+ ((parseFloat(value.productPrice) + parseFloat(value.productTax))*value.productQty).toFixed(2)+'</td>';
//cart_html += '<td>×</td>';
cart_html += '</tr>';
checkButton(value.uProductID);
total_items += value.productQty;
shipping += parseFloat(productCart[i].shippingmethod);
}
}
k++;
}
Here I am uploading this link http://harvey.binghamton.edu/~rnaik1/myForm.html where you can see how my scroll up n down button is working in javascript but now I am working with Ajax request to a php script on the server to retrieve all of the data from the database table.
Here is the link for the work i have done:http://harvey.binghamton.edu/~rnaik1/myScrollform.html
Everything is working fine for me except scroll up and scroll down button.
Once you add 5 records in a list after entering 6th record it will show latest 5 records.
I want to make the scrollup and down button working for myScrollform.html in the same way as in myForm.html. Any help would be helpful to me and appreciated.
Here is my code:
<html>
<head>
<title>My Scrolling Data Form</title>
<script src="./jquery-1.11.0.min.js"></script>
</head>
<body bgcolor="silver">
<center><h1>My Scrolling Data Form</h1>
<div id="scrollbar">
<input type="button" name="up" id="scrollup" value="Scroll Up" >
<input type="button" name="up" id="scrolldown" value="Scroll Down">
</div>
<div id="mydata" style="height: 200px; overflow-y: scroll">
Currently we have no data
</div>
<hr>
<div id="addformdata">
<form name="addForm" >
To add data to the list, fill in the form below and click on "Add"
<br>
<td><input type="text" id="name" name="namei" value=""></td>
<td><input type="text" id="ssn" name="ssni" value="" ></td>
<td><input type="text" id="date" name="birthi" value="" ></td>
<td><input type="text" id="currency" name="xxxxi" value=""></td>
<input type="button" name="add" value="Add" onclick="validateForm(); return false;">
</form>
</div>
</center>
</body>
</html>
<script type="text/javascript">
// Arrays to store values
var name_Array=new Array();
var ssn_Array=new Array();
var date_Array=new Array();
var currency_Array=new Array();
var Index = 0;
var first = 0;
var last = 0;
var scrolled = 0;
var random_Array=new Array();
$(document).ready(function(){
fetchdata();
$("#scrollup").on("click" ,function(){
// alert('hi');
// scrolled=scrolled+100;
$("#mydata").animate({
scrollTop: 0
}, 800);
});
$("#scrolldown").on("click" ,function()
{
// console.log($elem.height());
$("#mydata").animate({
scrollTop: 5000
}, 800);
});
});
function deleteRecord(id)
{
if(confirm('Are you Sure you Want to delete this record')){
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"action": "delete",
"id": id
},
success:function(data)
{
fetchdata()
console.log('success');
}
});
}
}
function fetchdata()
{
// var scrolled=0
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"action": "fetch"
},
success:function(data)
{
$("#mydata").html('')
$("#mydata").html(data);
console.log('success');
}
});
}
function validateForm()
{
var name = document.getElementById("name");
var ssn = document.getElementById("ssn");
var date = document.getElementById("date");
var currency = document.getElementById("currency");
var error = "";
//Name validation
if(name.value=="")
{
//Check for empty field
name.focus();
error = "Please Enter Name\n";
}
else
{ //format specifier
var letters = /^[a-zA-Z_ ]+$/;
//Check for format validation
if(!name.value.match(letters))
{
name.focus();
error = error + "Name contains only characters and spaces\nPlease Renter Name\n";
}
}
//Date validation
if(date.value=="")
{
//Check for empty field
date.focus();
error = error + "Please Enter Date\n";
}
else
{ //format specifier
var date_regex = /^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$/;
//check for format validation
if(!date.value.match(date_regex))
{
date.focus();
error = error + "Date must be in mm/dd/yyyy format\nPlease Renter Date\n";
}
}
//SSN validation
if(ssn.value=="")
{
//check for empty field
ssn.focus();
error = error + "Please Enter SSN\n";
}
else
{
//format specifier
var numbers = /^\d{3}((-?)|\s)\d{2}((-?)|\s)\d{4}$/g;
//check format validation
if(!ssn.value.match(numbers))
{
ssn.focus();
error = error + "SSN must be in xxx-xx-xxxx format\nPlease Renter SSN\n";
}
}
//Currency validation
if(currency.value=="")
{
//check for empty field
currency.focus();
error = error + "Please Enter Currency\n";
}
else
{
//format specifier
var pattern = /^(\$)\d+(\.\d{1,3})?$/g ;
//check for format validation
if(!currency.value.match(pattern))
{
currency.focus();
error = error + "Currency must be in $xx.xxx format\nPlease Renter Currency\n";
}
}
if(error)
{
alert(error);
return false;
}
else
{
var name = document.getElementById("name").value;
var ssn = document.getElementById("ssn").value;
var date = document.getElementById("date").value;
var currency = document.getElementById("currency").value;
console.log(name)
adduser(name,ssn,date,currency);
return true;
}
}
function insertToList()
{
// call a function to validate the fields
var valid_function = validateForm();
if(valid_function == false)
{
return false;
}
else
{
//get the entered values from fields
var name = document.getElementById("name");
var ssn = document.getElementById("ssn");
var date = document.getElementById("date");
var currency = document.getElementById("currency");
// push the values in the array
name_Array.push(name.value);
ssn_Array.push(ssn.value);
date_Array.push(date.value);
currency_Array.push(currency.value);
// generate and push random number in the array to search the record in array and then delete that record.
random_Array.push(Math.floor((Math.random()*100)+1));// http://stackoverflow.com/questions/8610635/how-do-you-use-math-random-to-generate-random-ints
//function to insert values to list
InsertValues();
// clear the fields after each add
clearFields();
alert("Record is successfully added to above list.");
// set focus back on the name field
name.focus();
}
}
function clearFields()
{
document.getElementById("name").value = "";
document.getElementById("ssn").value = "";
document.getElementById("date").value = "";
document.getElementById("currency").value = "";
}
// function to add to the list
function InsertValues()
{
var temp = 1,temp1 = 1,index = 0,i=0;
index = name_Array.length - 5;
for(i=0;i< name_Array.length;i++)
{
// when only first 5 entries are added to the list
if(name_Array.length>5)
{
// skip the first values so that only top 5 are shown in the list
if(temp>s)
{
if(temp1==5)
{
last = i;
}
else if(temp1==1)
{
first = i;
Index = i;
}
if(temp1<=5)
{
//initialise values of fields to the list
var str = "name" + temp1;
document.getElementById(str).value = name_Array[i];
str = "ssn" + temp1;
document.getElementById(str).value = ssn_Array[i];
str = "birth" + temp1;
document.getElementById(str).value = date_Array[i];
str = "xxxx" + temp1;
document.getElementById(str).value = currency_Array[i];
str = "random" + temp1;
document.getElementById(str).value = random_Array[i];
}
temp1++;
}
}
else
{
var str = "name" + temp;
document.getElementById(str).value = name_Array[i];
str = "ssn" + temp;
document.getElementById(str).value = ssn_Array[i];
str = "birth" + temp;
document.getElementById(str).value = date_Array[i];
str = "xxxx" + temp;
document.getElementById(str).value = currency_Array[i];
str = "random" + temp;
document.getElementById(str).value = random_Array[i];
}
temp++;
}
}
// Delete a record from the list
function delete_a_Record(record)
{
var remove = 0,i=0,j=1;
var name = document.getElementById("name" + record.value);
var delRecord = document.getElementById("random" + record.value);
if(name.value)
{
remove = 1;
}
// check for the existence of record
if(remove == 1)
{
if(confirm("Click on 'OK' to delete the record\n"))
{
while(i < random_Array.length)
{
if(delRecord.value==random_Array[i])
{
// if yes then remove that record from list
name_Array.splice(i, 1);
ssn_Array.splice(i, 1);
date_Array.splice(i, 1);
currency_Array.splice(i, 1);
random_Array.splice(i, 1);
}
i++;
}
// make entire list empty
while(j <= 5)
{
var str = "name" + j;
document.getElementById(str).value = "";
str = "ssn" + j;
document.getElementById(str).value = "";
str = "birth" + j;
document.getElementById(str).value = "";
str = "xxxx" + j;
document.getElementById(str).value = "";
str = "random" + j;
document.getElementById(str).value = "";
j++;
}
//call this function again to insert values in the list
InsertValues();
record.checked = false;
}
}
else
{
alert("Nothing to delete in this record.");
record.checked = false;
}
}
// function to perform scrollUp n scrollDown
function handleScrolling(type)
{
var j,k,temp2 = 1;
// perform scroll only when there are more than 5 records in the list
if(name_Array.length>5)
{ // scroll up
if(type==1)
{
first--; // decrement the pointer to see upper records
if(first>=0)
{
for (j = first; j < name_Array.length; j++) // its showing top most record from jth position
{
var str = "name" + temp2;
document.getElementById(str).value = name_Array[j];
str = "ssn" + temp2;
document.getElementById(str).value = ssn_Array[j];
str = "birth" + temp2;
document.getElementById(str).value = date_Array[j];
str = "xxxx" + temp2;
document.getElementById(str).value = currency_Array[j];
str = "random" + temp2;
document.getElementById(str).value = random_Array[j];
temp2++;
}
}
else
{
alert("Top of the list is reached\n");
first++;// increment the pointer to see lower records
}
}
else // scroll down
{
// increment the start point to see lower records if any
first++;
if(first<=Index)
{
for (k = first; k < name_Array.length; k++) //its showing bottom most record in the list from kth position
{
var str = "name" + temp2;
document.getElementById(str).value = name_Array[k];
str = "ssn" + temp2;
document.getElementById(str).value = ssn_Array[k];
str = "birth" + temp2;
document.getElementById(str).value = date_Array[k];
str = "xxxx" + temp2;
document.getElementById(str).value = currency_Array[k];
str = "random" + temp2;
document.getElementById(str).value = random_Array[k];
temp2++;
}
}
else
{
alert("Bottom most record is reached\n");
first--;//decrement the pointer to see upper records if any
}
}
}
else
{
alert("Scrolling strikes for records more than 5\n");
return false;
}
}
function adduser(name,ssn,date,currency)
{
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"name": name,
"ssn": ssn,
"date": date,
"currency": currency,
"action": "add"
},
success:function(data){
console.log('success');
fetchdata();
}
});
}
</script>
//php file
<?php
extract($_POST);
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error($con));
}
//mysql_select_db("ripal");
mysql_select_db("test");
//$sql = "SELECT * FROM user WHERE id = '" . $q . "'";
if ($action == 'add') {
$sql = "INSERT INTO myform(name,ssn,date,income)VALUES('" . mysql_real_escape_string($name) . "','" . mysql_real_escape_string($ssn) . "','" . mysql_real_escape_string($date) . "','" . mysql_real_escape_string($currency) . "')";
// echo $sql;
mysql_query($sql);
echo mysql_insert_id();
} else if ($action == 'fetch') {
$sql = "select * from myform";
// echo $sql;
$result = mysql_query($sql);
$str = '<form name="myForm">
<table width="page">
<tr>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td></td>
</tr>';
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name = $row['name'];
$ssn = $row['ssn'];
$date = $row['date'];
$currency = $row['income'];
$str.='<tr>
<td><input type="radio" id="' . $id . '" name="del" onclick="deleteRecord(this.id);"></td>
<td><input readonly type="text" value="' . $name . '" id="name1" name="name"></td>
<td><input readonly type="text" value="' . $ssn . '" id="ssn1" name="ssn"></td>
<td><input readonly type="text" value="' . $date . '" id="birth1" name="birth"></td>
<td><input readonly type="text" value="' . $currency . '" id="xxxx1" name="xxxx"><input type="hidden" name="random1" id="random1"></td>
</tr>';
}
}
$str.=' <tr>
<td colspan="5" id="scrollCount" align="center" style="padding-top:10px;"> </td>
</tr>
</table>
</form>';
if (mysql_num_rows($result) == 0) {
echo 'No data in Our Database please add one or more';
} else {
echo $str;
}
} else if ($action = 'delete') {
$sql = "DELETE from myform WHERE id=$id";
// echo $sql;
$result = mysql_query($sql);
echo $result;
}
mysql_close($con);