I need some fresh eyes on what I'm trying to do. I'm working on making our inventory spreadsheet more accurate and email a person when we get low on something. I got most of the code done, there's one part that I'm having issues with and it's where we add a number to certain parts of the spreadsheet. To be more exact, I'm trying to have a menu with multiple text areas for each part, and each text area will relate to the number that we just bought of that part.
My current code for this section has an array that will create and add the textarea to the panel and the part that is labeled in the spreadsheet. A button that will add the text area to the spreadsheet.
My issue that I'm having is correctly setting up the .addCallbackElement() with an array and get whats in the text area to the spreadsheet.
Can anyone see where I am making the mistake, or possible recommendation at something better that I could do?
Thanks for any help that is given
function addBit() {
var ss = SpreadsheetApp.getActive();
var sheet0 = ss.getSheetByName('Inventory');
var lastrow0 = sheet0.getLastRow();
//var ui = SpreadsheetApp.getUi();
//data for each column that we need
var datarange0 = sheet0.getRange('D2:D'+lastrow0);
var datarange1 = sheet0.getRange('E2:E'+lastrow0);
var datarange2 = sheet0.getRange('F2:F'+lastrow0);
var datarange3 = sheet0.getRange('K2:K'+lastrow0);
var datarange4 = sheet0.getRange('I2:I'+lastrow0);
var data0 = datarange0.getValues();// Column D
var data1 = datarange1.getValues();// Column E
var data2 = datarange2.getValues();// Column F
var data3 = datarange3.getValues();// Column K
var data4 = datarange4.getValues();// Column I
var app = UiApp.createApplication();
app.setHeight(500).setWidth(500);
var scroll = app.createScrollPanel().setPixelSize(500,500);
var vpanel0 = app.createVerticalPanel();
var vpanel1 = app.createVerticalPanel();
var hpanel0 = app.createHorizontalPanel();
var apanel = app.createAbsolutePanel();
var text = new Array(lastrow0-1);
//creating labels and text areas for each part for the first column in the menu
for (var i = 0; i <= Math.round((lastrow0 - 2)/2); i++) {
var hpanel = app.createHorizontalPanel();
var label = app.createLabel(data0[i]+ ' ' + data1[i] + 'mm ('+ Math.round(data2[i]) + 'mil)');
text[i] = app.createTextArea().setName('text'+i).setSize(50,20).setValue(0);//.setId('text'+i);
hpanel.add(text[i]);
hpanel.add(label);
vpanel0.add(hpanel);
}
//creating labels and text areas for each part for the second column in the menu
for (var i = Math.round((lastrow0 - 2)/2) + 1; i <= lastrow0 - 2; i++) {
var hpanel = app.createHorizontalPanel();
var label = app.createLabel(data0[i]+ ' ' + data1[i] + 'mm ('+ Math.round(data2[i]) + 'mil)');
text[i] = app.createTextArea().setName('text'+i).setSize(50,20).setValue(0);//.setId('text'+i);
hpanel.add(text[i]);
hpanel.add(label);
vpanel1.add(hpanel);
}
//Creating handlers for the text areas
var thandler = app.createServerHandler('addition');
for (var j = 0; j <= lastrow0 - 2; j++) {
thandler.addCallbackElement(text[j]).setId('text'+i);
}
//when button is hit, the function 'addition' will run
var addButton = app.createButton("Add", thandler);
hpanel0.add(vpanel0);
hpanel0.add(vpanel1);
apanel.add(hpanel0);
apanel.add(addButton);
scroll.add(apanel);
app.add(scroll);
return app;
}
function addition(e){
var app = UiApp.getActiveApplication();
var ss = SpreadsheetApp.getActive();
var sheet0 = ss.getSheetByName('Inventory');
var lastrow0 = sheet0.getLastRow();
//data for each column
var datarange3 = sheet0.getRange('K2:K'+lastrow0);
var datarange4 = sheet0.getRange('I2:I'+lastrow0);
var data3 = datarange3.getValues();// Column K
var data4 = datarange4.getValues();// Column I
var text0 = new Array(lastrow0-1);
//text0[] will have what was in each text area
for (var i = 0; i <= lastrow0 - 2; i++) {
text0[i] = e.parameter.('text' + 1);
}
//for loop will add what was in the text area to columns 'Qty Acq' and 'Current Stock'
for (var j = 0; j <= lastrow0-2; j++) {
var k = j+2;
var v = data3[j] + text0[j];
var x = data4[j] + text0[j]
sheet0.getRange('M' + k).setValue(v);
sheet0.getRange('N' + k).setValue(x);
}
app.close();
}
Use the highest level panel (scrollpanel I guess) as a single callbackElement, it will automatically include all the child widgets.
Related
I have already written a code to extract content from a csv file and add each chunk of text on each layer of illustrator. At the moment I could add content for fixed artboard. But I need to add separate art board while keeping the width 23mm. So, artboard height similar to content height of the particular layer. I'm getting an error "TypeError: text.parentArtboard is undefined"
Kindly help me to resolve the above issue.
var csv = '''clipName,Trans,fname
A1 ,test Text1,A1_ENG
A2 ,Pigment dyed fabric w.,A2_ENG
A3 ,UPF 50+ fabric. Only covered areas are protected. To maintain this level of protection the garment must be rinsed in fresh water after each use.,A3_ENG
A4 ,Light colours may become transparent when wet,A4_ENG'''
/* var csv_file = File.openDialog();
csv_file.open("r")
var csv = csv_file.read();
csv_file.close() */
var lines = csv.split("\n");
// MAIN -------------------------------------------------------------
// make character styles
var FONT1 = make_style("font1", "ArialMT", 5.5);
// process lines
for (var i=1; i<lines.length; i++) {
var data = get_data_from(lines[i]);
make_layer(data.name)
var text = make_text(data.contents);
apply_styles(text);
put_in_center(text);
// Create a new artboard
//artboard()
}
// END
// functions --------------------------------------------------------
function make_style(style_name, font_name, size) {
// try to add a new style
try { var style = app.activeDocument.characterStyles.add(style_name) }
// or pick a style with the same name if it exists already
catch(e) { var style = app.activeDocument.characterStyles.getByName(style_name) }
//var style = app.activeDocument.characterStyles.add(style_name);
style.characterAttributes.size = size;
style.characterAttributes.textFont = textFonts.getByName(font_name);
return style;
}
function addArtboard(text, artboardWidth ) {
// Get all layers in the text
var layers = text.layers;
// Set the artboard width to 23
var artboard = text.parentArtboard;
artboard.width = artboardWidth;
// Declare variable to keep track of content height
var contentHeight = 0;
// Loop through all layers
for (var i = 0; i < layers.length; i++) {
var layer = layers[i];
// Position the layer
layer.x = 0;
layer.y = contentHeight;
// Update content height
contentHeight += layer.height;
}
// Set the artboard height based on the content height
artboard.height = contentHeight;
}
function get_data_from(line) {
var arr = line.split(",");
var fname = arr[2]
var VL1 = arr[0];
var VL2 = arr[1];
//alert("Your message here...", fname);
//return {"name":Fname, "contents":[VL1, VL2, VL3, VL4,VL5, VL6, VL7, VL8, VL9]};
return {"name":fname, "contents":[VL2]};
}
//string.includes(substring)
function rearrangeText(text, artboardWidth) {
// Split the text into words
var words = text.split(" ");
var rearrangedText = "";
var currentLine = "";
// Loop through each word
for (var i = 0; i < words.length; i++) {
var word = words[i];
// If the current line + the next word would exceed the artboard width
if (currentLine.length + word.length > artboardWidth) {
// Add the current line to the rearranged text
rearrangedText += currentLine + "\n";
// Reset the current line
currentLine = "";
}
// Add the word to the current line
currentLine += word + " ";
}
// Add the last line to the rearranged text
rearrangedText += currentLine;
return rearrangedText;
}
function make_layer(layer_name) {
var new_layer = app.activeDocument.layers.add();
new_layer.name = layer_name;
}
function make_text(array) {
var text = app.activeDocument.textFrames.add();
text.contents = rearrangeText(array.join("\n"),23);
addArtboard(text.contents,23) //Try to add new artboar based on the text content size
return text;
}
function artboard() {
var layers = app.activeDocument.layers;
var textLayers = [];
for (var i = 0; i < layers.length; i++) {
if (layers[i].kind == LayerKind.TEXT) {
textLayers.push(layers[i]);
}
}
var width = 23; // width in mm
for (var i = 0; i < textLayers.length; i++) {
var textLayer = textLayers[i];
var textBounds = textLayer.bounds;
var artboardWidth = width * app.activeDocument.rulerUnits;
var artboardHeight = textBounds[3] - textBounds[1];
var artboard = app.activeDocument.artboards.add(textBounds);
artboard.width = artboardWidth;
artboard.height = artboardHeight;
textLayer.move(artboard);
}
}
function to_center(artboard, item){
var artboard_x = artboard.artboardRect[0] + artboard.artboardRect[2];
var artboard_y = artboard.artboardRect[1] + artboard.artboardRect[3];
var x = (artboard_x - item.width)/2;
var y = (artboard_y + item.height)/2;
item.position = [x, y];
}
function apply_styles(text) {
// not the best piece of code, I'm sure it can be done better
text.textRange.paragraphAttributes.justification = Justification.CENTER;
FONT1.applyTo(text.textRange);
}
function put_in_center(obj) {
var rect = app.activeDocument.artboards[0].artboardRect;
var page_w = rect[2] - rect[0];
var page_h = rect[1] - rect[3];
var shift_x = page_w/2 - obj.width/2;
var shift_y = -page_h/2 + obj.height/2;
obj.position = [rect[0] + shift_x, rect[1] + shift_y];
}
When I remove the function addArtboard(text, artboardWidth ) all content will be nicely rearrange based on the width of the artboard. But, artboard size doesn't change due to the code error.
Experts kindly help me with this.
Image of the content arrangement on illustrator layers are mention below
If understand the task correctly you can add this function into the code:
function distribute_texts_and_create_artboards() {
const mm = 2.83465; // mm/pt
var shift_x = 30 * mm; // horizontal shifs for texts
var width = 25 * mm; // artboard width
var doc = app.activeDocument;
var frames = doc.textFrames;
// move all the frames and create an artboard for the every text frame
for (var i=0; i<frames.length; i++) {
var frame = frames[i];
frame.translate(shift_x * i, 0); // move the frame horizontally
var frame_x1 = frame.geometricBounds[0];
var frame_y1 = frame.geometricBounds[1];
var frame_x2 = frame.geometricBounds[2];
var frame_y2 = frame.geometricBounds[3];
var artboard_x = frame_x1 - (width - frame.width)/2;
var artboard_y = frame_y1;
var artboard_w = frame_x2 + (width - frame.width)/2;
var artboard_h = frame.height;
var artboard_rect = [artboard_x, artboard_y, artboard_w, -artboard_h];
var new_ab = doc.artboards.add(artboard_rect); // create a new artboard
new_ab.name = frame.parent.name; // artboard name = layer name
// frame.position = [frame.position[0], frame.position[1]/2]; // to centred the frame vertically
}
doc.artboards[0].remove(); // delete the old first artboard
}
and call it at the end of the 'MAIN' section:
...
}
distribute_texts_and_create_artboards();
// END
...
and comment out the line:
// put_in_center(text);
It should give you the layout as follows:
Probably it makes sense to tweak the vertical position of the frames of the artboards a bit. But since you haven't provided an example of desired result I left it as is, for now. Let me know if you need it or uncomment the line:
frame.position = [frame.position[0], frame.position[1]/2];
And you don't need the functions addArtboard() and artboard() anymore in the code.
Update
Here is the function that saves all the text frames from layers as separate PDFs into the same folder as current AI file. File names are the same as layer names.
function save_layers_as_pdfs() {
var doc = app.activeDocument;
// pdf options
var options = new PDFSaveOptions();
options.compatibility = PDFCompatibility.ACROBAT5;
options.generateThumbnails = true;
options.preserveEditability = false;
options.preset = "[Smallest File Size]";
var mm = 2.83465; // mm/pt
var width = 25 * mm; // artboard width
var layers = doc.layers;
for (var i=0; i<layers.length; i++) {
var layer = layers[i];
layer.hasSelectedArtwork = true;
if (app.selection.length == 0) continue;
app.copy();
app.selection = null;
// create a new file
var file = File(doc.path + '/' + layer.name + '.pdf');
var new_doc = app.documents.add();
app.paste();
// change the artboard size
var frame = new_doc.textFrames[0];
var frame_x1 = frame.geometricBounds[0];
var frame_y1 = frame.geometricBounds[1];
var frame_x2 = frame.geometricBounds[2];
var frame_y2 = frame.geometricBounds[3];
var artboard_x = frame_x1 - (width - frame.width)/2;
var artboard_y = frame_y1;
var artboard_w = frame_x1 + frame.width + (width - frame.width)/2;
var artboard_h = frame_y1 - frame.height;
doc.artboards[0].artboardRect = [artboard_x, artboard_y, artboard_w, artboard_h];
// save a pdf and close document
new_doc.saveAs(file, options);
new_doc.close(SaveOptions.DONOTSAVECHANGES);
}
}
You can call this function at the end of the MAIN section.
The result:
And make sure your csv data is correct: the separators, quote marks, tabulations, etc.
In a google sheets table, I use a script that allows me to count the cells in color in a column that displays dates as values. Each date over 11 days is colored in red, and my script works very well.
In another column, I indicate the name of each salesman.
What I would like is to be able to count the number of red cells that belong to each salesman.
The date column is column "G" and the salesman column is column "F" (In my script it doesn't matter because I indicate in which column to count).
My Sheet:
https://docs.google.com/spreadsheets/d/1BFd57xpFOJMOAjuRaiO6_cLCMMxQKDwi_TB6dOCDb9A/edit#gid=0
The formula for my script is:
=CompteCouleurs($G6:$G;C4)
"$G6:$G" is the range to count
"C4" is the sample of the color to search
My script is:
function SommeCouleurs(plage,couleur) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var formule = activeRange.getFormula();
var laplage = formule.match(/\((.*)\;/).pop();
var range = activeSheet.getRange(laplage);
var bg = range.getBackgrounds();
var values = range.getValues();
var lacouleur = formule.match(/\;(.*)\)/).pop();
var colorCell = activeSheet.getRange(lacouleur);
var color = colorCell.getBackground();
var total = 0;
for(var i=0;i<bg.length;i++)
for(var j=0;j<bg[0].length;j++)
if( bg[i][j] == color )
total=total+(values[i][j]*1);
return total;
};
function CompteCouleurs(plage,couleur) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var formule = activeRange.getFormula();
var laplage = formule.match(/\((.*)\;/).pop();
var range = activeSheet.getRange(laplage);
var bg = range.getBackgrounds();
var values = range.getValues();
var lacouleur = formule.match(/\;(.*)\)/).pop();
var colorCell = activeSheet.getRange(lacouleur);
var color = colorCell.getBackground();
var count = 0;
for(var i=0;i<bg.length;i++)
for(var j=0;j<bg[0].length;j++)
if( bg[i][j] == color )
count=count+1;
return count;
};
First, expand your area to G and F =CompteCouleurs($F6:$G;C4)
Then as you only take column G into account, you can omit for(var j=0;j<bg[0].length;j++)
Therefore you can check color in G and salesman in F as follows if( bg[i][1] == color && values[i][0] == salesman )
If you want to include the salesman as parameter, you will have to change the regex as follows to retrieve each argument (args will be an array)
var args = formule.match(/\(.*\)/g)[0].match(/[A-Z0-9:]+/g)
I recommand also to add a dummy parameter (checkbox) to update the calculation
Correction of your script:
function compteCouleursSi(plage, couleur, vendeur) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var formule = activeRange.getFormula();
// array of arguments
var args = formule.match(/(?<=\().*(?=\))/g)[0].split(/[;|,]/)
var laplage = args[0];
if (laplage.includes('!')) {
var range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(laplage.split('!')[0].replace(/'/g,'')).getRange(laplage.split('!')[1].trim());
}else{
var range = activeSheet.getRange(laplage);
}
var bg = range.getBackgrounds();
var values = range.getValues();
var lacouleur = args[1];
var color = activeSheet.getRange(lacouleur).getBackground();
var salesman = args[2];
var who = activeSheet.getRange(salesman).getValue()
var total = 0;
for (var i = 0; i < bg.length; i++)
if (bg[i][1] == color && values[i][0] == who)
total += 1;
return total;
};
function sommeCouleursSi(plage, couleur, vendeur) {
var activeRange = SpreadsheetApp.getActiveRange();
var activeSheet = activeRange.getSheet();
var formule = activeRange.getFormula();
// array of arguments
var args = formule.match(/(?<=\().*(?=\))/g)[0].split(/[;|,]/)
var laplage = args[0];
if (laplage.includes('!')) {
var range = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(laplage.split('!')[0].replace(/'/g,'')).getRange(laplage.split('!')[1].trim());
}else{
var range = activeSheet.getRange(laplage);
}
var bg = range.getBackgrounds();
var values = range.getValues();
var lacouleur = args[1];
var color = activeSheet.getRange(lacouleur).getBackground();
var salesman = args[2];
var who = activeSheet.getRange(salesman).getValue()
var total = 0;
for (var i = 0; i < bg.length; i++)
if (bg[i][1] == color && values[i][0] == who)
total += values[i][1];
return total;
};
I'm looking to create a spreadsheet where it logs data and the changes you make on it.
For example in sheet, I used a Google Script to do it but instead of only logging in a particular row when you change the data on Sheet1, it copies all the data you changed since the beginning on Sheet 2. I only want to log a particular row each time I make a change.
Here's my code
* Retrieves all the rows in the active spreadsheet that contain Yes
* in the Include column and copies them to the Report sheet.
*/
function myFunction() {
var sSheet = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = sSheet.getSheetByName("Sheet1");
var tarSheet = sSheet.getSheetByName("Sheet2");
var lastRow = srcSheet.getLastRow();
for (var i = 2; i <= lastRow; i++) {
var cell = srcSheet.getRange("B" + i);
var val = cell.getValue();
if (val == 'Yes') {
var srcRange = srcSheet.getRange("A" + i + ":D" + i);
var tarRow = tarSheet.getLastRow();
tarSheet.insertRowAfter(tarRow);
var tarRange = tarSheet.getRange("A" + (tarRow+1) + ":D" + (tarRow+1));
srcRange.copyTo(tarRange);
}
}
};
Can anyone please help?
Use onEdit(e)
function onEdit(e) {
var srcSheet = e.source.getActiveSheet();
if (srcSheet.getSheetName() !== 'Sheet1') { return; }
var row = e.range.rowStart;
var cols = 4;
var srcRange = srcSheet.getRange(row, 1, 1, cols);
var values = srcRange.getValues()[0];
if (values[1] == 'Yes') {
var tarSheet = e.source.getSheetByName('Sheet2');
tarSheet.appendRow(values);
}
}
I'm getting HTML from a forum url, and parsing the post count of the user from their profile page. I don't know how to write the parsed number into the Google spreadsheet.
It should go account by account in column B till last row and update the column A with count.
The script doesn't give me any errors, but it doesn't set the retrieved value into the spreadsheet.
function msg(message){
Browser.msgBox(message);
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Update")
.addItem('Update Table', 'updatePosts')
.addToUi();
}
function getPostCount(profileUrl){
var html = UrlFetchApp.fetch(profileUrl).getContentText();
var sliced = html.slice(0,html.search('Posts Per Day'));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
return postCount;
}
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var accountSheet = spreadSheet.getSheetByName("account-stats");
var statsLastCol = statsSheet.getLastColumn();
var accountCount = accountSheet.getLastRow();
var newValue = 0;
var oldValue = 0;
var totalNewPosts = 0;
for (var i=2; i<=accountCount; i++){
newValue = parseInt(getPostCount(accountSheet.getRange(i, 9).getValue()));
oldValue = parseInt(accountSheet.getRange(i, 7).getValue());
totalNewPosts = totalNewPosts + newValue - oldValue;
accountSheet.getRange(i, 7).setValue(newValue);
statsSheet.getRange(i,statsLastCol).setValue(newValue-todaysValue);
}
if(showAlert==false){
return 0;
}
msg(totalNewPosts+" new post found!");
}
function valinar(needle, haystack){
haystack = haystack[0];
for (var i in haystack){
if(haystack[i]==needle){
return true;
}
}
return false;
}
The is the first time I'm doing something like this and working from an example from other site.
I have one more question. In function getPostCount I send the function profileurl. Where do I declare that ?
Here is how you get the URL out of the spreadsheet:
function getPostCount(profileUrl){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var thisSheet = ss.getSheetByName("List1");
var getNumberOfRows = thisSheet.getLastRow();
var urlProfile = "";
var sliced = "";
var A_Column = "";
var arrayIndex = 0;
var rngA2Bx = thisSheet.getRange(2, 2, getNumberOfRows, 1).getValues();
for (var i = 2; i < getNumberOfRows + 1; i++) { //Start getting urls from row 2
//Logger.log('count i: ' + i);
arrayIndex = i-2;
urlProfile = rngA2Bx[arrayIndex][0];
//Logger.log('urlProfile: ' + urlProfile);
var html = UrlFetchApp.fetch(urlProfile).getContentText();
sliced = html.slice(0,html.search('Posts Per Day'));
var postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
sliced = sliced.slice(sliced.search('<dt>Total Posts</dt>'),sliced.length);
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
Logger.log('postCount: ' + postCount);
A_Column = thisSheet.getRange(i, 1);
A_Column.setValue(postCount);
};
}
You're missing var in front of one of your variables:
postCount = sliced.slice(sliced.search("<dd> ")+"<dd> ".length,sliced.search("</dd>"));
That won't work. Need to put var in front. var postCount = ....
In this function:
function updatePosts(){
if(arguments[0]===false){
showAlert = false;
} else {
showAlert=true;
}
There is no array named arguments anywhere in your code. Where is arguments defined and how is it getting any values put into it?
looking for a bit of help with my jQuery, (i know its not the best)
Currently have a form, split into 2 sides,
on the left I have a list of assests on the right is the liabilities
somewhat of a balance sheet for account, see the image below
the jquery in use just now, is a bit of a mess.. (sorry)
this code will calculate the field totals on each keyup request, which seems to work ok,
jQuery('#ass_cash, #ass_liquid, #ass_lifeinsu, #ass_covvalue, #ass_la1, #ass_la2, #ass_la3, #ass_realestate, #ass_auto1total, #ass_auto2total, #lib_mortgage, #lib_bankloan1, #lib_bankloan2, #lib_loansinsucomp, #lib_loanscreditunion, #lib_creditcards, #lib_od1, #lib_od2, #lib_od3, #lib_rent, #lib_mortgagemthpmt, #lib_bankloan1mthpmt, #lib_bankloan2mthpmt, #lib_loansinsucompmthpmt, #lib_loanscreditunionmthpmt, #lib_creditcardsmthpmt, #lib_od1mthpmt, #lib_od2mthpmt, #lib_od3mthpmt, #lib_rentmthpmt').keyup( function(){
// ASSESTS
var ass_cash = jQuery("#ass_cash").val();
var ass_liquid = jQuery("#ass_liquid").val();
var ass_lifeinsu = jQuery("#ass_lifeinsu").val();
var ass_covvalue = jQuery("#ass_covvalue").val();
var ass_la1 = jQuery("#ass_la1").val();
var ass_la2 = jQuery("#ass_la2").val();
var ass_la3 = jQuery("#ass_la3").val();
var ass_realestate = jQuery("#ass_realestate").val();
var ass_auto1total = jQuery("#ass_auto1total").val();
var ass_auto2total = jQuery("#ass_auto2total").val();
var ass_total = jQuery("#ass_total").val();
if(ass_cash==''){ ass_cash = 0; }
if(ass_liquid==''){ ass_liquid = 0; }
if(ass_lifeinsu==''){ ass_lifeinsu = 0; }
if(ass_covvalue==''){ ass_covvalue = 0; }
if(ass_la1==''){ ass_la1 = 0; }
if(ass_la2==''){ ass_la2 = 0; }
if(ass_la3==''){ ass_la3 = 0; }
if(ass_realestate==''){ ass_realestate = 0; }
if(ass_auto1total==''){ ass_auto1total = 0; }
if(ass_auto2total==''){ ass_auto2total = 0; }
var asssubtotal = parseInt(ass_cash) + parseInt(ass_liquid) + parseInt(ass_lifeinsu) + parseInt(ass_covvalue);
asssubtotal = asssubtotal + parseInt(ass_la1) + parseInt(ass_la2) + parseInt(ass_la3) + parseInt(ass_realestate);
asssubtotal = asssubtotal + parseInt(ass_auto1total) + parseInt(ass_auto2total);
var asstotal = jQuery('#ass_total');
asstotal.val(asssubtotal);
// LIABILITIES
var lib_mortgage = jQuery("#lib_mortgage").val();
var lib_bankloan1 = jQuery("#lib_bankloan1").val();
var lib_bankloan2 = jQuery("#lib_bankloan2").val();
var lib_loansinsucomp = jQuery("#lib_loansinsucomp").val();
var lib_loanscreditunion = jQuery("#lib_loanscreditunion").val();
var lib_creditcards = jQuery("#lib_creditcards").val();
var lib_od1 = jQuery("#lib_od1").val();
var lib_od2 = jQuery("#lib_od2").val();
var lib_od3 = jQuery("#lib_od3").val();
var lib_rent = jQuery("#lib_rent").val();
if(lib_mortgage==''){ lib_mortgage = 0; }
if(lib_bankloan1==''){ lib_bankloan1 = 0; }
if(lib_bankloan2==''){ lib_bankloan2 = 0; }
if(lib_loansinsucomp==''){ lib_loansinsucomp = 0; }
if(lib_loanscreditunion==''){ lib_loanscreditunion = 0; }
if(lib_creditcards==''){ lib_creditcards = 0; }
if(lib_od1==''){ lib_od1 = 0; }
if(lib_od2==''){ lib_od2 = 0; }
if(lib_od3==''){ lib_od3 = 0; }
if(lib_rent==''){ lib_rent = 0; }
var libsubtotal = parseInt(lib_mortgage) + parseInt(lib_bankloan1) + parseInt(lib_bankloan2) + parseInt(lib_loansinsucomp);
libsubtotal = libsubtotal + parseInt(lib_loanscreditunion) + parseInt(lib_creditcards) + parseInt(lib_od1) + parseInt(lib_od2);
libsubtotal = libsubtotal + parseInt(lib_od3) + parseInt(lib_rent);
var lib_subtotal = jQuery('#lib_subtotal'); lib_subtotal.val(libsubtotal);
// MONTHLY PAYMENTS
var lib_mortgagemthpmt = jQuery("#lib_mortgagemthpmt").val();
var lib_bankloan1mthpmt = jQuery("#lib_bankloan1mthpmt").val();
var lib_bankloan2mthpmt = jQuery("#lib_bankloan2mthpmt").val();
var lib_loansinsucompmthpmt = jQuery("#lib_loansinsucompmthpmt").val();
var lib_loanscreditunionmthpmt = jQuery("#lib_loanscreditunionmthpmt").val();
var lib_creditcardsmthpmt = jQuery("#lib_creditcardsmthpmt").val();
var lib_od1mthpmt = jQuery("#lib_od1mthpmt").val();
var lib_od2mthpmt = jQuery("#lib_od2mthpmt").val();
var lib_od3mthpmt = jQuery("#lib_od3mthpmt").val();
var lib_rentmthpmt = jQuery("#lib_rentmthpmt").val();
if(lib_mortgagemthpmt==''){ lib_mortgagemthpmt = 0; }
if(lib_bankloan1mthpmt==''){ lib_bankloan1mthpmt = 0; }
if(lib_bankloan2mthpmt==''){ lib_bankloan2mthpmt = 0; }
if(lib_loansinsucompmthpmt==''){ lib_loansinsucompmthpmt = 0; }
if(lib_loanscreditunionmthpmt==''){ lib_loanscreditunionmthpmt = 0; }
if(lib_creditcardsmthpmt==''){ lib_creditcardsmthpmt = 0; }
if(lib_od1mthpmt==''){ lib_od1mthpmt = 0; }
if(lib_od2mthpmt==''){ lib_od2mthpmt = 0; }
if(lib_od3mthpmt==''){ lib_od3mthpmt = 0; }
if(lib_rentmthpmt==''){ lib_rentmthpmt = 0; }
var lib_surplus = jQuery('#lib_surplus');
if(lib_surplus==''){ lib_surplus = 0; }
var subtotal = parseInt(lib_mortgagemthpmt) + parseInt(lib_bankloan1mthpmt) + parseInt(lib_bankloan2mthpmt) + parseInt(lib_loansinsucompmthpmt);
subtotal = subtotal + parseInt(lib_loanscreditunionmthpmt) + parseInt(lib_creditcardsmthpmt) + parseInt(lib_od1mthpmt) + parseInt(lib_od2mthpmt);
subtotal = subtotal + parseInt(lib_od3mthpmt) + parseInt(lib_rentmthpmt);
var totalmthpmt = jQuery('#lib_totalmthpmt');
totalmthpmt.val(subtotal);
var assets_total = jQuery('#ass_total').val();
var lib_subtotal = jQuery('#lib_subtotal').val();
var lib_surplus = jQuery('#lib_surplus');
if(assets_total==''){ assets_total = 0; }
if(lib_subtotal==''){ lib_subtotal = 0; }
if(lib_surplus==''){ lib_surplus = 0; }
var surplus = assets_total - lib_subtotal;
lib_surplus.val(surplus);
// THIS IS THE PART THAT ISNT WORKING
//surplus/deficit
//var lib_total = jQuery('#lib_total').val();
//if(lib_total==''){ lib_total = 0; }
//var lib_totalmthpmt = jQuery('#lib_totalmthpmt').val();
//if(lib_totalmthpmt==''){ lib_totalmthpmt = 0; }
//var surplustotal = lib_total - lib_totalmthpmt;
//jQuery('#mthsurplus').val(surplustotal);
});
you can see the section which is causing issues above, its the calculation between the subtotal (minus) Surplus to generate the total,
each field for asset has a class .asset
each libability has class .liability
each monthly payment field has class .liabilitymth
Ive tried doing the jQuery('.asset').each(function() and trying to generate the total in the asset field, same for the other 2, sections,
the greyed out boxes are "readonly", were the calculations should appear.
ASSETS: The total on the left side of the page will be the total assets.
LIABILITIES: The 'Subtotal' will reflect the sum of the Liability column.
SURPLUS: This will represent the difference (Negative'-' OR Positive'+'), between the Assets & Liabilities-Balance column.
TOTAL(Right Side): This is to create a 'Balance Sheet'effect, so when you look at it, the calculation should reflect the same figure as the 'Total' over on the Asset side (Left side).
MONTHLY-SURPLUS/ DEFICIT: This should reflect the net difference in Total Income Revenue, either negative OR positive (Figure found From the Employment Tab), when compared with the total of the 'Monthly Payment' column.
this is where my jQuery falls flat on its face, there has to be an easier way to calculate the field totals, anyone shed any light on this, or have a much better use of code, rather than wrapping it all under a very large keyup request :)
This can give you the head start:
var totalAss = 0;
jQuery('.asset').each(function(){
var value = parseFloat(this.value);
if (value)
totalAss += value;
});
jQuery('#ass_total').val(totalAss);
There is indeed some easy way. Do things like that
on all classes means .assets , .liability and .liabilitymth do this on document.ready
$(function()
{
$('.assets , .liability ,.liabilitymth').each(function()
{
var value = $(this).val();
if(value == "")
{
$(this).val('000.00');
}
});
});
And now
var total_assets = 0;
$('.assets').keyup(function(){
var number = $(this).val();
total_assets += parseInt(number);
});
After that
$('#total_assets').val(total_assets);
If you do the calculation in the keyup or any other key events, then there will be a problem of keeping track of the old data that was entered. For ex., at an instant you had typed 50 and then you made it to 500 and then you made it to say 30. Then, the keyevent will not be able to figure out the difference between both the old and new data. You will have to write some logic to figure out the old and the new updated data and then depending on that you will have to update the final value. It is better if you can code something like this...
http://jsfiddle.net/AvSEG/