MYSQL Join and create Distinct json - mysql

I have the following select
if ($result = $mysqli->query("SELECT
a.quoteID, a.quoteTitle , a.notes, c.web_path
FROM quotes a
INNER JOIN users_files b on b.user_id = a.quoteID
INNER JOIN files c on c.id = b.file_id ORDER BY quoteID ASC"))
{
$tempArray = array();
while($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray);
}
which gets me information I need.
[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/23.pdf"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/22.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/21.jpeg"},{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"\/surplusAdmin3\/upload\/20.jpeg"},{"quoteID":"2","quoteTitle":"Kaitlin","notes":"Smith","web_path":"\/surplusAdmin3\/upload\/24.jpg"},{"quoteID":"8","quoteTitle":"Bryar2","notes":"Long","web_path":"\/surplusAdmin3\/upload\/17.png"},{"quoteID":"11","quoteTitle":"Avram","notes":"Allison","web_path":"\/surplusAdmin3\/upload\/4.jpg"}]
I now need to get my result as:
[{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path1":"\/surplusAdmin3\/upload\/23.pdf","web_path2":"\/surplusAdmin3\/upload\/22.jpeg","web_path3":"\/surplusAdmin3\/upload\/21.jpeg","web_path4":"\/surplusAdmin3\/upload\/20.jpeg"}]
I am not looking to re-do the MYSQL statement I just need to create a new array in the format I need.
I have the following code:
var currentQuoteID =0;
var dataChanged = [];
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
console.log(' current quote '+ currentQuoteID + ' = '+ e["quoteID"] + 'file count = '+ fileCount);
if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
else
{
console.log('just add the filename array Row = ' +arrayRow );
// need to insert to the array arrayRow
// dataChanged.push('web_path'+fileCount,e["web_path"]);
toPush = 'web_path'+fileCount+'"'+':'+'"'+ e["web_path"];
var field = 'web_path'+fileCount;
var data = e["web_path"];
var tempArray = [field,data];
dataChanged.push(toPush);
dataChanged.field = data;
//dataChanged = dataChanged.concat(tempArray);
fileCount = fileCount +1;
}
currentQuoteID = e["quoteID"];
console.log('stuff '+ JSON.stringify(dataChanged));
});
The result I am getting is :
dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image"},"web_path1","/surplusAdmin3/upload/22.jpeg"]
What I need is
dataChanged = [{"quoteID":"1","quoteTitle":"Title for 1","notes":"Deal no 1","web_path":"/surplusAdmin3/upload/23.pdf","Type":"image","web_path1","/surplusAdmin3/upload/22.jpeg"}]
But I cannot workout what I need to do here.

Got it working as follows:
// loop through and add field 'Type' can all be done in one loop.
dataReturned.forEach(function(e){
if (typeof e === "object" ){
e["Type"] = "other";
// console.log('stuff '+e['Type'][i] )
}
});
//loop through and workout the file type
dataReturned.forEach(function(e){
if (typeof e === "object" ){
var ext = e['web_path'].substr(e['web_path'].lastIndexOf('.') + 1);
if ( (ext === 'jpeg' ) || ( ext === 'jpg' )|| ( ext === 'png' )|| ( ext === 'gif' ) || ( ext === 'pdf' ))
{ e["Type"] = "image"; }
//console.log(e['web_path']);
// console.log('stuff '+ JSON.stringify(e))
}
});
// create a new array formated as needed
var currentQuoteID =0;
var arrayRow = -1 ;
var fileCount = 0;
dataReturned.forEach(function(e){
e["quoteID"] + 'file count = '+ fileCount);
if ( currentQuoteID !== e["quoteID"]) {dataChanged.push(e); arrayRow = arrayRow + 1; fileCount = 1}
else
{
//console.log('just add the filename array Row = ' +arrayRow );
// need to insert to the array arrayRow
// dataChanged.push('web_path'+fileCount,e["web_path"]);
var field = 'web_path'+fileCount;
var data = webPath+e["web_path"];
var tempArray = [field,data];
dataChanged[arrayRow]['web_path'+fileCount] = data
fileCount = fileCount +1;
}
currentQuoteID = e["quoteID"];
console.log('stuff '+ JSON.stringify(dataChanged));
});

Related

Automatically Delete rows in Google sheet script

I'm trying to write a google script that will updates the sensor data google sheet.This part is ok.
And I try to add a function clearRange(), when the data updated to 100 rows and delete the first 100 rows and reupdate the data. Is there something that I'm missing here?
function doGet(e) {
Logger.log( JSON.stringify(e) );
var sheet_id = 'XXXXXXXXXXXXXXXXXXXXX'; // Spreadsheet ID
var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet();
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else if(e.parameter != 'undefined'){
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "GMT+8", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temperature':
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
break;
case 'humidity':
rowData[3] = value; // Humidity in column D
result += ' ,Humidity Written on column D';
break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
else if (newRow==100)
{
clearRange();
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
function clearRange() {
sheet.deleteRows(1,100);
}
Try this:
function doGet(e) {
var sheet_id = 'XXXXXXXXXXXXXXXXXXXXX'; // Spreadsheet ID
var sh = SpreadsheetApp.openById(sheet_id).getActiveSheet();
var newRow = sh.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else if (e.parameter != 'undefined') {
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "GMT+8", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
var value = e.parameter[param].replace(/['"]+/g, '');
switch (param) {
case 'temperature':
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
break;
case 'humidity':
rowData[3] = value; // Humidity in column D
result += ' ,Humidity Written on column D';
break;
default:
result = "unsupported parameter";
}
}
var newRange = sh.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
else if (newRow == 100) {
sh.deleteRows(1, 100);
}
return ContentService.createTextOutput(result);
}

Want to add Email sent function incase my temps are more than 8 appsscript

I have a code that I use to log temperatures into Google sheets..Code written in Appsscript. In this code, i want to add a function in the case 'temperature' that can send mail in case the incoming temperature to be logged is more than 8.. How can I do that? Someone help in that kind of code?
function doGet(e) {
Logger.log( JSON.stringify(e) );
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else {
var sheet_id = '1hKXZEIx160TwXi5yUztGBDijNaGgAOjKWSmY-Mowo9M'; // Spreadsheet ID
//var sheetActive = SpreadsheetApp.openById("ID");
//var sheet = sheetActive.getSheetByName("Name");
var sheetActive = SpreadsheetApp.openById(sheet_id);
var sheet = sheetActive.getSheetByName("Theatre");
//var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet().getSheetByName("Sheet3");
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "Africa/Nairobi", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temperature':
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
// if(){
// }
break;
// case 'humidity':
// rowData[3] = value; // Humidity in column D
// result += ' ,Humidity Written on column D';
// break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
Email Sent if value greater than 8
function doGet(e) {
Logger.log( JSON.stringify(e) );
var result = 'Ok';
if (e.parameter == 'undefined') {
result = 'No Parameters';
}
else {
var sheet_id = '1hKXZEIx160TwXi5yUztGBDijNaGgAOjKWSmY-Mowo9M'; // Spreadsheet ID
//var sheetActive = SpreadsheetApp.openById("ID");
//var sheet = sheetActive.getSheetByName("Name");
var sheetActive = SpreadsheetApp.openById(sheet_id);
var sheet = sheetActive.getSheetByName("Theatre");
//var sheet = SpreadsheetApp.openById(sheet_id).getActiveSheet().getSheetByName("Sheet3");
var newRow = sheet.getLastRow() + 1;
var rowData = [];
var Curr_Date = new Date();
rowData[0] = Curr_Date; // Date in column A
var Curr_Time = Utilities.formatDate(Curr_Date, "Africa/Nairobi", 'HH:mm:ss');
rowData[1] = Curr_Time; // Time in column B
for (var param in e.parameter) {
Logger.log('In for loop, param=' + param);
var value = stripQuotes(e.parameter[param]);
Logger.log(param + ':' + e.parameter[param]);
switch (param) {
case 'temperature':
Logger.log(
rowData[2] = value; // Temperature in column C
result = 'Temperature Written on column C';
Logger.log(`Date: ${new Date()} Value:${value}`);//Please add this
if(parseInt(value) > 8){
GmailApp.sendEmail('recipient emal','Subject',"message");
}
break;
// case 'humidity':
// rowData[3] = value; // Humidity in column D
// result += ' ,Humidity Written on column D';
// break;
default:
result = "unsupported parameter";
}
}
Logger.log(JSON.stringify(rowData));
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
return ContentService.createTextOutput(result);
}
function stripQuotes( value ) {
return value.replace(/^["']|['"]$/g, "");
}
GmailApp.sendEmail()

Invalid assignment left-hand side. (line 1, file "Code") after if statements are added

The error "Invalid assignment left-hand side." only started to occur after the if statements are added.It used to be ok til i added the variables and if statements.
Tried using single '|' for or.
function auto() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var QA = ss.getSheetByName("Quality Alert");
var QAdata = QA.getRange(3,1,QA.getLastRow() - 2,29).getValues();
QAdata.forEach(function(row, i){
var customer = row[1] ;
var part = row[2] ;
var s = row[3] ;
var id = row[4] ;
var fid = row[5] ;
var defect = row[6] ;
var desc = row[7] ;
var reject1 = row[8] ;
var reject2 = row[9] ;
var ok = row[10] ;
var url = row[11] ;
var depart = row[12] ;
if( 0 < depart <= 7){
Part1.sendEmail()
}
if( depart = 8 ){
Part2.sendEmail()
}
if( depart = 9){
Part3.sendEmail()
}
if( depart = 10 || depart = 11){
Part4.sendEmail()
}
if( 10 < depart <= 15){
Part5.sendEmail()
}
});// End Bracket for QA Data
}
Expected result is when var depart (a number from 1 to 15) is entered, it will run a particular code from the library(PartN.sendEmail).
Fixed it by using "==" instead of "=".

"Lock wait timeout exceeded" when sending data from Google Sheets to MySQL

I wrote an Apps Script macro to send data from a Google spreadsheet to a MySQL table. In a first time, in delete some rows in the table and then I add rows in this table. I sometimes get a "Lock wait timeout exceeded; try restarting transaction" error. Sometimes it runs after 100 seconds, sometimes 4 minutes.
I don't understand what is wrong with this code.
//classeur.insertSheet("feuillebis")
//feuillebis=classeur.getSheets()[1]
//var feuillebis=classeur.getSheetByName('feuillebis')
var classeur = SpreadsheetApp.getActiveSpreadsheet() ;
var feuille = classeur.getActiveSheet();
var host = "107.167.186.180";
var databaseName = "eatology";
var userName = "root";
var password = "eatology";
var port = 3306;
var tableName = "weekly_order";
var url = 'jdbc:mysql://' + host + ':' + port + '/' + databaseName;
var nbrow = feuille.getMaxRows()
function Send_Weekly_Order_To_Data_Base() {
///here are all the connection parameters
var classeur = SpreadsheetApp.getActiveSpreadsheet();
var feuille = classeur.getActiveSheet();
var nbrow = feuille.getMaxRows();
var host = "107.167.186.180";
var databaseName = "eatology";
var userName = "root";
var password = "eatology";
var port = 3306;
var tableName = "weekly_order";
var url = 'jdbc:mysql://' + host + ':' + port + '/' + databaseName;
var conn = Jdbc.getConnection(url, userName, password);
conn.setAutoCommit(false);
///get the weekly_order as an array from the sql
var rowcount = 0;
var stmt2 = conn.createStatement();
var results = stmt2.executeQuery("SELECT * FROM eatology.weekly_order");
while (results.next()) {
if (results.getInt(1) > rowcount){
rowcount = results.getInt(1)
}
}
conn.commit();
results.close();
stmt2.close();
///delete the rows from the current week where we are running the macro
var timezone1 = classeur.getSpreadsheetTimeZone();
var date1 = Utilities.formatDate(feuille.getRange(2, 2).getValue(), timezone1, "yyyy-MM-dd");
var date2 = Utilities.formatDate(feuille.getRange(2, 3).getValue(), timezone1, "yyyy-MM-dd");
var date3 = Utilities.formatDate(feuille.getRange(2, 4).getValue(), timezone1, "yyyy-MM-dd");
var date4 = Utilities.formatDate(feuille.getRange(2, 5).getValue(), timezone1, "yyyy-MM-dd");
var date5 = Utilities.formatDate(feuille.getRange(2, 6).getValue(), timezone1, "yyyy-MM-dd");
var date6 = Utilities.formatDate(feuille.getRange(2, 7).getValue(), timezone1, "yyyy-MM-dd");
///clear the table weekly-order in the database
var stmt1 = conn.createStatement();
var result = stmt1.executeUpdate("DELETE FROM eatology.weekly_order where `Date` = " + "'" + date1 + "'" +" or `Date` = " + "'" + date2 + "'" +" or `Date` = " + "'" + date3 + "'" +" or `Date` = "+ "'" + date4 + "'" +" or `Date` = " + "'" + date5 + "'" +" or `Date` = "+ "'" + date6 + "'" );
//var result = stmt1.executeUpdate("DELETE FROM eatology.weekly_order where `Date` = " + "'" + date1 +"'");
conn.commit();
stmt1.close();
conn.close();
rowcount = rowcount + 1;
var conn = Jdbc.getConnection(url, userName, password);
conn.setAutoCommit(false);
var stmt = conn.prepareStatement('INSERT INTO eatology.weekly_order '
+ '(`Uid`, `Date`, `MP`, `Cname`, `Pname`, `Breakfast`, `Snack1`, `Lunch`, `Snack2`, `Dinner`) values (?,?,?,?,?,?,?,?,?,?)');
var program_name_line = 0;
var array = feuille.getRange(1, 1, nbrow, 7).getValues();
for (var j = 1; j < 7; j = j + 1) {
var inside = 0;
var i = 1;
while (array[i][0] != "Total" && i < 1000) {
i = i + 1
var color = feuille.getRange(i + 1, j + 1).getBackgrounds()
var fi1 = array[i][0].toString();
var fij = array[i][j].toString();
var empty = (fij == "");
var already = 0;
var test11111 = (color != "#5d31ce");
var cas1 = ((empty == false) && (fi1 != "Total") && (inside == 0));
var cas2 = (color == "#5d31ce" && inside == 1);
var cas3 = (empty == false);
if ((fi1 != "Total") && (inside == 0) && color != "#5d31ce") {
program_name_line = i;
inside = 1;
if (empty == false) {
var Uid = rowcount;
var Date1 = (Utilities.formatDate(array[1][j], timezone1, "yyyy-MM-dd"));
var MP = (array[program_name_line][0]);
var place = ((fij).indexOf("-"));
var length = (fij.length);
var Pname = ((fij).substring(place + 1, length));
var Cname = ((fij).substring(0, place));
var list = (meal(MP, Pname));
var Breakfast = list[0];
var Snack1 = list[1];
var Lunch = list[2];
var Snack2 = list[3];
var Dinner = list[4];
if (MP == "TM") {
var Breakfast = 1;
var Snack1 = 1;
var Lunch = 1;
var Snack2 = 1;
var Dinner = 1;
}
rowcount = rowcount + 1;
stmt.setInt(1, Uid);
stmt.setString(2, Date1);
stmt.setString(3, MP);
stmt.setString(4, Cname);
stmt.setString(5, Pname);
stmt.setInt(6, Breakfast);
stmt.setInt(7, Snack1);
stmt.setInt(8, Lunch);
stmt.setInt(9, Snack2);
stmt.setInt(10, Dinner);
stmt.addBatch();
}
}
else if (color == "#5d31ce" && inside == 1) {
inside = 0;
}
else if (empty == false && color != "#5d31ce") {
var Uid = rowcount ;
var Date1 = (Utilities.formatDate(array[1][j], timezone1, "yyyy-MM-dd"));
var MP = (array[program_name_line][0].toString());
var place = ((fij).indexOf("-"));
var length = (fij.length);
var Pname = ((fij).substring(place + 1, length));
var Cname = ((fij).substring(0, place));
var list = (meal(MP, Pname));
var Breakfast = (list[0]);
var Snack1 = (list[1]);
var Lunch = (list[2]);
var Snack2 = (list[3]);
var Dinner = (list[4]);
if (MP == "TM") {
var Breakfast = 1;
var Snack1 = 1;
var Lunch = 1;
var Snack2 = 1;
var Dinner = 1;
}
rowcount = rowcount+1;
stmt.setInt(1, Uid);
stmt.setString(2, Date1);
stmt.setString(3, MP);
stmt.setString(4, Cname);
stmt.setString(5, Pname);
stmt.setInt(6, Breakfast);
stmt.setInt(7, Snack1);
stmt.setInt(8, Lunch);
stmt.setInt(9, Snack2);
stmt.setInt(10, Dinner);
stmt.addBatch();
}
}
}
stmt.executeBatch();
conn.commit();
stmt.close();
conn.close();
}
function meal(MP, Pname){
var result= [0, 0, 0, 0, 0]
//in order to know if we have two snacks or only one because if the programm has more than 1200 cal, there are two snacks, otherwise, only one snack
var two_snacks = 1
if (MP.indexOf("1200") > -1) {
two_snacks = 0
}
//if the program type is '3'
if (Pname.indexOf("3") > -1) {
result[0] = 1;
result[1] = 1;
result[2] = 1;
result[4] = 1;
if (two_snacks == 1) {
result[3] = 1;
}
}
//if the program type is '2'
if (Pname.indexOf("2") > -1 && Pname.indexOf("S") == -1) {
result[0] = 1;
result[1] = 1;
result[2] = 1;
if (two_snacks == 1) {
result[3] = 1;
}
}
//if there is the B letter
if (Pname.indexOf("B") > -1) {
result[0] = 1;
}
//if there is the L letter
if (Pname.indexOf("L") > -1) {
result[2] = 1;
}
//if there is the D letter
if (Pname.indexOf("D") > -1) {
result[4] = 1;
}
//if there is the 2S letter
if (Pname.indexOf("2S") > -1) {
result[1] = 1;
result[3] = 1;
}
//if there is the 1S letter
if (Pname.indexOf("1S") > -1) {
result[1] = 1;
result[1] = 1;
}
return result
}

How to calculate taking input from four fields in yii2 dynamic form

I've five fields- rate, qty. discount, cgst_percent, cgst_amount.
I want to calculate cgst_amount. The formula should be -
cgst_amount = ((rate*qty - (rate*qty*discount)/100)*cgst_percent)/100
To Start with simple steps, I tried cgst_amount = rate*qty
The javascript part is as below -
<?php
/* start getting the cgst */
$script = <<< JS
function getGst(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var qtyvar = ratevar = discvar = cgstpercentvar = cgstvar = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if (myString == "rate") {
fetch1 = index.concat("-qty");
fetch2 = index.concat("-discount");
fetch3 = index.concat("-cgst_rate");
} else if (myString == "qty") {
fetch1 = index.concat("-rate");
fetch2 = index.concat("-discount");
fetch3 = index.concat("-cgst_rate");
} else if (myString == "discount"){
fetch1 = index.concat("-qty");
fetch2 = index.concat("-rate");
fetch3 = index.concat("-cgst_rate");
} else {
fetch1 = index.concat("-qty");
fetch2 = index.concat("-rate");
fetch3 = index.concat("-discount");
}
temp1 = $("#productsales-"+fetch1+"").val();
temp2 = $("#productsales-"+fetch2+"").val();
temp3 = $("#productsales-"+fetch3+"").val();
//alert (temp2);
if (!isNaN(temp1) && temp1.length != 0) {
ratevar = temp1;
}
if (isNaN(temp2) || temp2.length != 0) {
discvar = temp2;
}
if (isNaN(temp3) || temp3.length != 0) {
cgstpercentvar = temp3;
}
qtyvar = item.val();
if (isNaN(qtyvar) || qtyvar.length == 0) {
qtyvar = 0;
}
//alert (qtyvar);
if (!isNaN(qtyvar) && !isNaN(ratevar) && !isNaN(discvar) && !isNaN(cgstpercentvar)) {
cgstvar = (parseFloat(qtyvar) * parseFloat(ratevar)).toFixed(2);
}
cgstField = "productsales-".concat(index).concat("-cgst_amount");
$("#"+cgstField+"").val(cgstvar);
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the cgst */
?>
Whn I key in rate and qty I get multiply of them as output in cgst_amount textbox. No problem so far. As soon as I key in anything in discount,the same texts are getting written in cgst_amount as output.
I'm not quite sure about the javascript part.
It is an extension of - Calculate from 3 inputfield in dynamic form yii2 and Calculate 3 fields and display the result in the 4th in yii2 dynamic form
If I work on the full formula, the javascript calculation part becomes - cgstvar = ((((parseFloat(ratevar) * parseFloat(qtyvar)) - (parseFloat(ratevar) * parseFloat(qtyvar) * parseFloat(discvar))/100) * parseFloat(cgstpercentvar))/100).toFixed(2);
And the example is as below image -
The actual result should have been - 5.43. Instead I'm getting -0.00
You meshed up with fields and variables, i have updated a script a bit :
function getGst(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var qtyvar = ratevar = discvar = cgstpercentvar = cgstvar = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
quantity = index.concat("-qty");
rate = index.concat("-rate");
discount = index.concat("-discount");
cgstRate = index.concat("-cgst_rate");
temp1 = $("#productsales-"+quantity+"").val();
temp2 = $("#productsales-"+rate+"").val();
temp3 = $("#productsales-"+discount+"").val();
temp4 = $("#productsales-"+cgstRate+"").val();
if (isNaN(temp1) || temp1.length != 0) {
qtyvar = temp1;
}
if (!isNaN(temp2) && temp2.length != 0) {
ratevar = temp2;
}
if (isNaN(temp3) || temp3.length != 0) {
discvar = temp3;
}
if (isNaN(temp4) || temp4.length != 0) {
cgstpercentvar = temp4;
}
if (!isNaN(qtyvar) && !isNaN(ratevar) && !isNaN(discvar) && !isNaN(cgstpercentvar)) {
cgstvar = ((((parseFloat(ratevar) * parseFloat(qtyvar)) - (parseFloat(ratevar) * parseFloat(qtyvar) * parseFloat(discvar))/100) * parseFloat(cgstpercentvar))/100).toFixed(2);
}
cgstField = "productsales-".concat(index).concat("-cgst_amount");
$("#"+cgstField+"").val(cgstvar);
}