jquery: Summing values after dynamic delete of content gets NaN - javascript

here is my js:
function sumAllFields() {
var priceSum = 0;
$(".price").each(function () {
var o = $(this).parent().parent().index();
priceSum += Number($("#area" + o).text()) * $("#price" + o).val();
})
$("#sumPrice, #printSumPrice").html(priceSum.toFixed(2));
}
And here is relevant html:
<tbody id="tableBody">
<tr class="tableRow" id="tableRow0">
<td><input class="idNumber" id="idNumber0" type="number"></td>
<td><input class="description" id="description0" type="text"></td>
<td class="dimA" id="dimA0">520</td>
<td class="dimB" id="dimB0">785</td>
<td><input class="pcs" id="pcs0" type="number"></td>
<td class="area" id="area0">2.46</td>
<td><input class="price" id="price0" type="number"></td>
<td class="noprint"><span class="closed">×</span></td>
</tr>
<!-- and a few more in between... -->
<tr class="tableRow" id="tableRow8">
<td><input class="idNumber" id="idNumber8" type="number"></td>
<td><input class="description" id="description8" type="text"></td>
<td class="dimA" id="dimA8">510</td>
<td class="dimB" id="dimB8">785</td>
<td><input class="pcs" id="pcs8" type="number"></td>
<td class="area" id="area8">0.80</td>
<td><input class="price" id="price8" type="number"></td>
<td class="noprint"><span class="closed">×</span></td>
</tr>
</tbody>
What I am trying to do is to automatically sum all .price fields after one <tr> is dynamically deleted, and all I get is NaN. Before I delete any row, I get a nice number, but after I delete any rows, I get NaN.

It is because of the logic you have used to find the sibling price/area element. Assume you have added 4 items, so you have elements like area0/area1/area2/area3. Now you are deleting row 2 so the element area1 is no longer present then in your each loop in the second iteration o becomes 1 then it tries to find element #area1 but there is no such element which results in Number($("#area" + o).text()) returning NaN.
Try
function sumAllFields() {
var priceSum = 0;
$(".price").each(function () {
var $tr = $(this).closest('tr');
priceSum += (+$tr.find(".area").text() * +this.value) || 0;
})
$("#sumPrice, #printSumPrice").html(priceSum.toFixed(2));
}
Demo: Fiddle

Lets iterate table rows directly:
function sumAllFields() {
var priceSum = 0;
$('.tableRow').each(function () {
var row = $(this);
priceSum += (parseFloat(row.find('.area').text())
* parseFloat(row.find('.price').val())) || 0;
})
$('#sumPrice, #printSumPrice').html(priceSum.toFixed(2));
}

Related

How copy and paste excel columns to HTML table with inputs?

I want to copy and paste excel columns or any similar lists into HTML table. I have found this code, but there is an issue. It pastes data like a row. So how can I change It to paste like a column? Thanks in advance.
$(document).ready(function() {
$('td input').bind('paste', null, function (e) {
$this = $(this);
setTimeout(function () {
var columns = $this.val().split(/\s+/);
var i;
var input = $this;
for (i = 0; i < columns.length; i++) {
input.val(columns[i]);
if( i % 3 !== 2){
input = input.parent().next().find('input');
} else{
input = input.parent().parent().next().find('input');
}
}
}, 0);
});
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
</thead>
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text"></td>
</tr>
</tbody>
</table>
Here is solution for you:
$(document).ready(function() {
$('td input').bind('paste', null, function(e) {
$input = $(this);
setTimeout(function() {
var values = $input.val().split(/\s+/),
row = $input.closest('tr'),
col = $input.closest('td').index();
console.log(col);
for (var i = 0; i < values.length; i++) {
row.find('input').eq(col).val(values[i]);
row = row.next();
}
}, 0);
});
});

jQuery calculate sum text fields if checked

I am trying to calculate the sum of text fields from a row which are checked.
My code works fine, but the problem which I am facing is my only calculate the value of first row only and it to previous result every time instead of adding current text field value.
Here is working fiddle:
https://jsfiddle.net/infohassan/27L6wvgw/
Here is my JS code:
$(document).ready(function(){
var $checkboxes = $('input[name^="txtChecked"]');
$checkboxes.change(function() {
$('input[name^="txtChecked"]').each(function() {
var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
calculateTotal();
});
});
});
function calculateTotal() {
var total = 0;
$('input[name^="txtChecked"]:checked').each(function(){
var val = parseFloat($('input[name^="txtCostAmount"]').val());
total += val;
});
$('input[name="txtNetAmount"]').val(total);
}
I cleaned your event handler...
And I made the .each() loop look for the text input which is on the same tr as the checkbox...
UpdatedFiddle
$(document).ready(function(){
var $checkboxes = $('input[name^="txtChecked"]');
$checkboxes.change(function() {
//$('input[name^="txtChecked"]').each(function() {
//var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
calculateTotal();
//});
});
});
function calculateTotal() {
var total = 0;
$('input[name^="txtChecked"]:checked').each(function(){
var val = parseFloat($(this).parents("tr").find('input[name^="txtCostAmount"]').val());
total += val;
});
$('input[name="txtNetAmount"]').val(total);
}
$(document).ready(function(){
var $checkboxes = $('input[name^="txtChecked"]');
$checkboxes.change(function() {
// var countCheckedCheckboxes = $checkboxes.find(':checked').length;
calculateTotal();
});
});
function calculateTotal() {
var total = 0;
$('input[name^="txtChecked"]:checked').each(function(index, item){
var parent = $(item).closest('tr');
var val = parseFloat(parent.find('input[name^="txtCostAmount"]').val());
total += val;
});
$('input[name="txtNetAmount"]').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th></th>
<th>Items</th>
<th>Cost</th>
</thead>
<tbody>
</tbody>
<tr>
<td><input name="txtChecked0" type="checkbox"></td>
<td>Item Name 1</td>
<td><input class="form-control input-sm" name="txtCostAmount0" value="3500" type="text"></td>
</tr>
<tr>
<td><input name="txtChecked1" type="checkbox"></td>
<td>Item Name 2</td>
<td><input class="form-control input-sm" name="txtCostAmount1" value="4500" type="text"></td>
</tr>
<tr>
<td><input name="txtChecked2" type="checkbox"></td>
<td>Item Name 3</td>
<td><input class="form-control input-sm" name="txtCostAmount2" value="4500" type="text"></td>
</tr>
</table>
<p>NetAmount <input class="form-control" name="txtNetAmount" value="0.00" readonly="" type="text"></p>

jquery - get html string of table cells

I have some HTML that is being generated by some server-side code. The HTML that's generated looks like this:
<table id="myChoices">
<tr>
<td><input type="radio" name="choice" value="1" /></td>
<td>Monday</td>
<td>Mar 7</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="2" /></td>
<td>Tuesday</td>
<td>Mar 8</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="3" /></td>
<td>Wednesday</td>
<td>Mar 9</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="4" /></td>
<td>Thursday</td>
<td>Mar 10</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="5" /></td>
<td>Friday</td>
<td>Mar 11</td>
</tr>
</table>
When a user makes a choice, I need to get the two cells next to it. For example, if someone chooses the third option, I'm trying to get the following:
<td>Wednesday</td><td>Mar 9</td>
In my attempt to do this, I have the following jQuery:
function getHtml() {
var html = '';
var item = $("#myChoices input[type='radio']:checked");
if (item.length > 0) {
var grandparent = item.parent().parent();
var cells = grandparent.children();
var html = '';
for (var i = 0; i < cells.length; i++) {
if (i > 0) {
var cellHtml = cells[i];
html += cellHtml;
}
}
}
return html;
}
Unfortunately, my approach is not working. When I do the following:
var test = getHtml();
console.log(test);
I see the following in the console window:
[object HTMLTableCellElement][object HTMLTableCellElement]
Why? How do I get the actual HTML string?
Use outerHTML, instead you are storing the jQuery object in the variable.
var cellHtml = cells[i];
should be
var cellHtml = cells[i].outerHTML;
JS
function getHtml() {
var item = $("#myChoices input[type='radio']:checked");
if (item.length > 0) {
var grandparent = item.closest('tr'),
cells = grandparent.children();
var html = '';
for (var i = 1; i < cells.length; i++) {
html += cells[i].outerHTML + ' ';
}
}
return html;
}
js Fiddle
I propose you change the script a bit to simplify the process altogether.
$("#myChoices input").change( function() {
var string = $(this).parent().nextAll("td").text();
});
Variable "string" will contain the text you are looking for.
I believe you could just use something simple like:
$("input[type='radio']:checked").parents("tr").first().text();
Example: http://codepen.io/cchambers/pen/ONNawo
JSFIDDLE DEMO
Use this instead
var cellHtml = cells[i].outerHTML;
Complete JS
var html = '';
var item = $("#myChoices input[type='radio']:checked");
if (item.length > 0) {
var grandparent = item.parent().parent();
var cells = grandparent.children();
var html = '';
for (var i = 0; i < cells.length; i++) {
if (i > 0) {
var cellHtml = cells[i].outerHTML; //change here
html += cellHtml;
}
}
}
console.log(html);
Result format:
<td>Monday</td><td>Mar 7</td>
The easiest way would be to use the .html() method on a dynamic tr which contains the other two td elements.
A trick is to clone them then wrap them in a tr and get the html of that
var others = $(this).closest('td').siblings().clone();
alert( others.wrapAll('<tr>').parent().html());
$(function(){
$('#myChoices [name="choice"]').on('change', function(){
var others = $(this).closest('td').siblings().clone();
alert( others.wrapAll('<tr>').parent().html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myChoices">
<tr>
<td><input type="radio" name="choice" value="1" /></td>
<td>Monday</td>
<td>Mar 7</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="2" /></td>
<td>Tuesday</td>
<td>Mar 8</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="3" /></td>
<td>Wednesday</td>
<td>Mar 9</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="4" /></td>
<td>Thursday</td>
<td>Mar 10</td>
</tr>
<tr>
<td><input type="radio" name="choice" value="5" /></td>
<td>Friday</td>
<td>Mar 11</td>
</tr>
</table>
In a function form it would be
function getHtml() {
var item = $("#myChoices input[type='radio']:checked");
var otherTD = item.closest('td').siblings().clone();
return otherTD.wrapAll('<tr>').parent().html();
}
You could use jquery's siblings method:
var textContents = $("#myChoices input[type='radio']:checked").siblings().html();

Using For-Loop to make hidden table rows appear when populated

I'm trying to pass data from one table to be used in another on the same page in javascript. The second table has rows 2-n hidden and I'd like them to dynamically appear when they're populated with data from the first table.
The first table that can be filled out looks like this:
<h3><em>Per Serving</em></h3>
<form name="ingredient-table">
<datalist id="ingredients">
<option value="Creatine Monohydrate">
<option value="St. John's Wort">
<option value="5-HTP">
<option value="Magnesium">
<option value="Magnesium Citrate">
<option value="Vitamin A">
<option value="Vitamin D3">
<option value="Cocoa">
<option value="Stevia">
<option value="Lavender Root Extract">
</datalist>
<table border="1" style="padding: 5px;">
<tr>
<td>Ingredient Name</td>
<td>Amount (in Mg)</td>
<td>% Carrier</td>
<td>$$/Kilo</td>
<td></td>
<td>Total Carrier Volume</td>
<td>Total Ingredient Volume</td>
</tr>
<tr>
<td><input type="text" id="a" list="ingredients"></input></td>
<td><input type="number" id="b"> Mg</input></td>
<td><input type="number" id="c"></input> %</td>
<td><input id="d"></input></td>
<td><button type="button" onclick="calculate('a', 'b', 'c', 'd', 'e', 'f')">Calculate Final
Volume</button></td>
<td id="e"><input></input></td>
<td id="f"><input></input></td>
<td>New Ingredient</td>
</tr>
<tr id="row2" style="display: none;">
<td><input type="text" id="h" list="ingredients"></input></td>
<td><input type="number" id="i"> Mg</input></td>
<td><input type="number" id="j"></input> %</td>
<td><input id="k"></input></td>
<td><button type="button" onclick="calculate('h', 'i', 'j', 'k', 'l', 'm')">Calculate Final
Volume</button></td>
<td id="l"><input></input></td>
<td id="m"><input></input></td>
<td>New Ingredient</td>
<td>Delete Ingredient</td>
</tr>
<tr id="row3" style="display: none;">
<td><input type="text" id="o" list="ingredients"></input></td>
<td><input type="number" id="p"> Mg</input></td>
<td><input type="number" id="q"></input> %</td>
<td><input id="r"></input></td>
<td><button type="button" onclick="calculate('o', 'p', 'q', 'r', 's', 't')">Calculate Final
Volume</button></td>
<td id="s"><input></input></td>
<td id="t"><input></input></td>
<td>New Ingredient</td>
<td>Delete Ingredient</td>
</tr>
<tr id="row4" style="display: none;">
<td><input type="text" id="v" list="ingredients"></input></td>
<td><input type="number" id="w"> Mg</input></td>
<td><input type="number" id="x"></input> %</td>
<td><input id="y"></input></td>
<td><button type="button" onclick="calculate('v', 'w', 'x', 'y', 'z', 'a1')">Calculate Final
Volume</button></td>
<td id="z"><input></input></td>
<td id="a1"><input></input></td>
<td>New Ingredient</td>
<td>Delete Ingredient</td>
</tr>
<tr id="row5" style="display: none;">
<td><input type="text" id="a3" list="ingredients"></input></td>
<td><input type="number" id="a4"> Mg</input></td>
<td><input type="number" id="a5"></input> %</td>
<td><input id="a6"></input></td>
<td><button type="button" onclick="calculate('a3', 'a4', 'a5', 'a6', 'a7', 'a8')">Calculate
Final Volume</button></td>
<td id="a7"><input></input></td>
<td id="a8"><input></input></td>
<td>New Ingredient</td>
<td>Delete Ingredient</td>
</tr>
</table>
</form>
The second table that accepts the data from the above table is this:
<h3>Per Bottle</h3>
<button type="button" onclick="bottle_volume('td1', 'td2', 'td3', 'td4', 'td5', 'td6', 'td7',
'td8','td9', 'td10', 'td11', 'td12', 'td13', 'td14', 'td15', 'td16', 'td17', 'td18', 'td19',
'td20')">Click to Calculate Bottle Totals</button>
<table border="1" style="padding: 5px;">
<tr>
<td>Ingredient</td>
<td>Total Amount of Carrier</td>
<td>Total Per Bottle</td>
<td>Total Cost Per Bottle</td>
</tr>
<tr id="outputRow1">
<td id="td1"><input></input></td>
<td id="td2"><input></input></td>
<td id="td3"><input></input></td>
<td id="td4"><input></input></td>
</tr>
<tr id="outputRow2" style="display: none;">
<td id="td5"><input></input></td>
<td id="td6"><input></input></td>
<td id="td7"><input></input></td>
<td id="td8"><input></input></td>
</tr>
<tr id="outputRow3" style="display: none;">
<td id="td9"><input></input></td>
<td id="td10"><input></input></td>
<td id="td11"><input></input></td>
<td id="td12"><input></input></td>
</tr>
<tr id="outputRow4" style="display: none;">
<td id="td13"><input></input></td>
<td id="td14"><input></input></td>
<td id="td15"><input></input></td>
<td id="td16"><input></input></td>
</tr>
<tr id="outputRow5" style="display: none;">
<td id="td17"><input></input></td>
<td id="td18"><input></input></td>
<td id="td19"><input></input></td>
<td id="td20"><input></input></td>
</tr>
<tr>
<td id="td21"><strong>Totals</strong></td>
<td id="td22"></td>
<td id="td23"></td>
<td id="td24"></td>
</tr>
</table>
The for-loop I use on the second table to make the rows appear is this:
var rowArray = ["outputRow1", "outputRow2", "outputRow3", "outputRow4", "outputRow5"];
for (i = 0; i < rowArray.length; i++) {
if (document.getElementById(rowArray[i]).innerHTML !== "") {
document.getElementById(rowArray[i]).style.display = 'table row';
}
else {
document.getElementById(rowArray[i]).style.display = 'none';
}
}
This doesn't cause the hidden rows to appear when they're populated. It doesn't seem to have any effect at all, and also does not cause any errors to appear in the javascript console.
The entire function that happens when you hit the button "Click to Calculate Bottle Totals"
is bottle_volume('td1', 'td2',...) and it looks like this:
var bottle_volume = function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11,
arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20) {
var ing1Value = calculate('a', 'b', 'c', 'd', 'e', 'f');
var ing1 = ing1Value[0];
var ing1_carrier = ing1Value[3]*30;
var ing1_volume = ing1Value[4]*30;
var ing1_cost = (ing1_volume/1000000)*ing1Value[2];
var name1 = document.getElementById(arg1).innerHTML = ing1;
var carrier1 = document.getElementById(arg2).innerHTML = ing1_carrier.toFixed(2)*1;
var ing_volume1 = document.getElementById(arg3).innerHTML = ing1_volume.toFixed(2)*1;
var ingCost1 = document.getElementById(arg4).innerHTML ="$" + ing1_cost.toFixed(2)*1;
var ing2Value = calculate('h', 'i', 'j', 'k', 'l', 'm');
var ing2 = ing2Value[0];
var ing2_carrier = ing2Value[3]*30;
var ing2_volume = ing2Value[4]*30;
var ing2_cost = (ing2_volume/1000000)*ing2Value[2];
var name2 = document.getElementById(arg5).innerHTML = ing2;
var carrier2 = document.getElementById(arg6).innerHTML = ing2_carrier.toFixed(2)*1;
var ing_volume2 = document.getElementById(arg7).innerHTML = ing2_volume.toFixed(2)*1;
var ingCost2 = document.getElementById(arg8).innerHTML = "$" + ing2_cost.toFixed(2)*1;
var ing3Value = calculate('o', 'p', 'q', 'r', 's', 't');
var ing3 = ing3Value[0];
var ing3_carrier = ing3Value[3]*30;
var ing3_volume = ing3Value[4]*30;
var ing3_cost = (ing3_volume/1000000)*ing3Value[2];
var name3 = document.getElementById(arg9).innerHTML = ing3;
var carrier3 = document.getElementById(arg10).innerHTML = ing3_carrier.toFixed(2)*1;
var ing_volume3 = document.getElementById(arg11).innerHTML = ing3_volume.toFixed(2)*1;
var ingCost3 = document.getElementById(arg12).innerHTML = "$" + ing3_cost.toFixed(2)*1;
var ing4Value = calculate('v', 'w', 'x', 'y', 'z', 'a1');
var ing4 = ing4Value[0];
var ing4_carrier = ing4Value[3]*30;
var ing4_volume = ing4Value[4]*30;
var ing4_cost = (ing4_volume/1000000)*ing4Value[2];
var name4 = document.getElementById(arg13).innerHTML = ing4;
var carrier4 = document.getElementById(arg14).innerHTML = ing4_carrier.toFixed(2)*1;
var ing_volume4 = document.getElementById(arg15).innerHTML = ing4_volume.toFixed(2)*1;
var ingCost4 = document.getElementById(arg16).innerHTML = "$" + ing4_cost.toFixed(2)*1;
var ing5Value = calculate('a3', 'a4', 'a5', 'a6', 'a7', 'a8');
var ing5 = ing5Value[0];
var ing5_carrier = ing5Value[3]*30;
var ing5_volume = ing5Value[4]*30;
var ing5_cost = (ing5_volume/1000000)*ing5Value[2];
var name5 = document.getElementById(arg17).innerHTML = ing5;
var carrier5 = document.getElementById(arg18).innerHTML = ing5_carrier.toFixed(2)*1;
var ing_volume5 = document.getElementById(arg19).innerHTML = ing5_volume.toFixed(2)*1;
var ingCost5 = document.getElementById(arg20).innerHTML = "$" + ing5_cost.toFixed(2)*1;
carrierPerBottle = ing1_carrier + ing2_carrier + ing3_carrier + ing4_carrier + ing5_carrier;
volumePerBottle = ing1_volume + ing2_volume + ing3_volume + ing4_volume + ing5_volume;
costPerBottle = ing1_cost + ing2_cost + ing3_cost + ing4_cost + ing5_cost;
document.getElementById("td22").innerHTML = carrierPerBottle.toFixed(2)*1;
document.getElementById("td23").innerHTML = volumePerBottle.toFixed(2)*1;
document.getElementById("td24").innerHTML = "$" + costPerBottle.toFixed(2)*1;
var rowArray = ["outputRow1", "outputRow2", "outputRow3", "outputRow4", "outputRow5"];
for (i = 0; i < rowArray.length; i++) {
if (document.getElementById(rowArray[i]).innerHTML !== "") {
document.getElementById(rowArray[i]).style.display = 'table row';
}
else {
document.getElementById(rowArray[i]).style.display = 'none';
}
};
};
I'm not sure what's wrong with my for-loop. I'm only using javascript for this and would prefer not to use jquery.
You can see the whole page here: Supplement Pricer
This is the rendered HTML for outputRow1:
<tr id="outputRow1">
<td id="td1"><input></input></td>
<td id="td2"><input></input></td>
<td id="td3"><input></input></td>
<td id="td4"><input></input></td>
</tr>
Same goes for outputRow2, outputRow3, outputRow4 and outputRow5, but they have different elements in their <td>.
When you call this function in Javascript:
var rowArray = ["outputRow1", "outputRow2", "outputRow3", "outputRow4", "outputRow5"];
for (i = 0; i < rowArray.length; i++) {
if (document.getElementById(rowArray[i]).innerHTML !== "") {
...
You're checking to see if outputRow1 has anything in it's Inner HTML, which it does. Therefore, it's going to display the row no matter what.
Basically, you need to check if their corresponding rows are set to display:none or display:table-row and display the outputRowN accordingly. I think this will work, but give it a try:
var rowArray = ["row2", "row3", "row4", "row5"]; // Skip row 1, always shows;
var outputArray = ["outputRow2", "outputRow3", "outputRow4", "outputRow5"];
for (i = 0; i < rowArray.length; i++) {
if (document.getElementById(rowArray[i]).getAttribute("style") != "display: none;"){
console.log("True");
document.getElementById(outputArray[i]).setAttribute("style", "");
} else {
console.log("False");
document.getElementById(outputArray[i]).setAttribute("style", "display: none;");
}
}
FINAL EDIT
Working Fiddle Example:
JSFiddle
if (document.getElementById(rowArray[i]).innerHTML !== "") {
document.getElementById(rowArray[i]).style.display = 'table row';
}
try changing the above code to (take out 'table row'):
if (document.getElementById(rowArray[i]).innerHTML !== "") {
document.getElementById(rowArray[i]).style.display = '';
}
i dont know if this will work, but its easier to post code in code format in the answer box then make a comment for it.
so i came up with another answer that requires at least one of the inputs of a row from table 1 to be filled out in order for the corresponding row in table 2 to be shown. i require one input to have at least some contents because if its based on if the row from table 1 is showing, you would just have a bunch of 0's in a bunch of rows in table 2.
heres the demo: http://jsfiddle.net/swm53ran/50/
calculate<br/><br/>
table 1<br/>
<table border="1" style="padding: 5px;">
<tr id="row1">
<td id="td1"><input></input></td>
<td id="td2"><input></input></td>
</tr>
<tr id="row2">
<td id="td3"><input></input></td>
<td id="td4"><input></input></td>
</tr>
<tr id="row3">
<td id="td5"><input></input></td>
<td id="td6"><input></input></td>
</tr>
</table>
<br/>
table 2<br/>
<table border="1" style="padding: 5px;" class="table2">
<tr id="outputRow1">
<td><input value="row1"></input></td>
<td><input></input></td>
</tr>
<tr id="outputRow2" style="display:none;">
<td><input value="row2"></input></td>
<td><input></input></td>
</tr>
<tr id="outputRow3" style="display:none;">
<td><input value="row3"></input></td>
<td><input></input></td>
</tr>
</table>
<script>
function populate() {
var rowArray = ["row2", "row3"];
var outArray = ["outputRow2", "outputRow3"];
for (i = 0; i < rowArray.length; i++) {
var inputs = document.getElementById(rowArray[i]).getElementsByTagName('input'); // get the inputs of table 1 row
var show = false;
for (j = 0; j < inputs.length; j++) {
if (inputs[j].value.length > 0) { // if at least one text box has contents, show = true
show = true;
}
}
if (show == true) {
document.getElementById(outArray[i]).style.display = "table-row";
}
else {
document.getElementById(outArray[i]).style.display = "none";
}
}
}
</script>
when the information from the text boxes of a given row are all empty in table 1, the row in table 2 will hide. hope this is suitable for your needs.

Multiply results using same function displayed on same page

Again with this one I have no idea what to call it but I will attempt to explain it the best I can.
I created a question similar to this before that did get answered but only because I wasn't 100% sure what I was looking for. Now I have worked out what I need etc..
So I have created this example, you will see that there are multiple inputs but they only work in the first column (due to no knowing how to make the others work). So now I need to get that working in ALL other columns using the same functions.
EXAMPLE
HTML:
<table>
<tr>
<th></th>
<th>Option1</th>
<th>Option2</th>
<th>Option3</th>
<th>Option4</th>
</tr>
<tr>
<td>Money</td>
<td><input type="number" id="money" /></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
</tr>
<tr>
<td>Upfront</td>
<td><input type="number" id="upfront" /></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
</tr>
<tr>
<td>Overall Price</td>
<td id="overallPrice"></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Discount</td>
<td><input type="number" id="discount" /></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
</tr>
<tr>
<td>Dicount Price</td>
<td id="discountPrice"></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Javascript/jQuery:
$(document).ready(function () {
$('input').keyup(function () {
overallPrice();
discountPrice();
});
});
function overallPrice() {
var cal1, cal2, result;
cal1 = parseFloat(document.getElementById("money").value);
cal2 = parseFloat(document.getElementById("upfront").value);
result = cal1 - cal2;
document.getElementById("overallPrice").innerHTML = "£" + result;
return result;
}
function discountPrice() {
var cal1, cal2, result;
cal1 = parseFloat(document.getElementById("discount").value);
cal2 = overallPrice();
result = cal2 - cal1;
document.getElementById("discountPrice").innerHTML = "£" + result;
}
So we have 2 inputs that will create the "Overall Price" and then the 3rd input will take that number and give the "Discount Price". If this was just 1 single column I could do it no problem but as I need this to work for all of the columns I'm not sure how I can do this using the same functions.
Hope this made some sort of sense if not let me know and I will try explain some more.
Here is a link to my other question, I added this part onto the end of it just encase you want to see where I started etc.
Other Question
*Note: There will be more then 2 sets of inputs, this is just an example. In my real version some of the inputs will not be used for certain columns and I will have to change some function to calculate certain columns differently. *
Here's another solution: FIDDLE
The idea is to find out which column the input is in (using .index()) and hand that index on to the overallPrice() and discountPrice() functions.
HTML
<table>
<tr>
<th></th>
<th>Option1</th>
<th>Option2</th>
<th>Option3</th>
<th>Option4</th>
</tr>
<tr id="money">
<td>Money</td>
<td><input type="number"/></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
</tr>
<tr id="upfront">
<td>Upfront</td>
<td><input type="number"/></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
</tr>
<tr id="overallPrice">
<td>Overall Price</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr id="discount">
<td>Discount</td>
<td><input type="number"/></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
<td><input type="number" /></td>
</tr>
<tr id="discountPrice">
<td>Dicount Price</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
JavaScript
$(document).ready(function () {
$('input').change(function () {
var $this = $(this),
$row = $this.closest('tr'),
$column = $this.closest('td'),
columnIndex = $row.find('td').index($column[0]);
//overallPrice(columnIndex);
discountPrice(columnIndex);
});
});
function overallPrice(column) {
var cal1, cal2, result;
cal1 = parseFloat($('#money td').eq(column).find('input').val() || '0');
cal2 = parseFloat($('#upfront td').eq(column).find('input').val() || '0');
result = cal1 - cal2;
$('#overallPrice td').eq(column).text("£" + result);
return result;
}
function discountPrice(column) {
var cal1, cal2, result;
cal1 = parseFloat($('#discount td').eq(column).find('input').val() || '0');
cal2 = overallPrice(column);
result = cal2 - cal1;
$('#discountPrice td').eq(column).text("£" + result);
}
Try giving a custom attribute to the individual cells(I've used count) and then accessing all the cells in the same column using that attribute(using the parentElement.childNodes thing wouldn't work because the parent in this instance would be the row, and not the column). I've passed the count value to your overallPrice and discountPrice functions, and modified the HTML a bit.
SCRIPT
$(document).ready(function () {
$('input').keyup(function () {
discountPrice(this.attributes.count.value);
});
});
function discountPrice(n) {
var cal1, cal2, result;
cal1 = parseFloat(document.getElementsByClassName("discount")[n-1].value);
cal2 = overallPrice(n);
result = cal2 - cal1;
document.getElementsByClassName("discountPrice")[n-1].innerHTML = "£" + result;
}
function overallPrice(n) {
var cal1, cal2, result;
cal1 = parseFloat(document.getElementsByClassName("money")[n-1].value);
cal2 = parseFloat(document.getElementsByClassName("upfront")[n-1].value);
result = cal1 - cal2;
document.getElementsByClassName("overallPrice")[n-1].innerHTML = "£" + result;
return result;
}
HTML Your rows should look like this:
<tr>
<td>Overall Price</td>
<td count="1" class="overallPrice"></td>
<td count="2" class="overallPrice"></td>
<td count="3" class="overallPrice"></td>
<td count="4" class="overallPrice"></td>
</tr>
FIDDLE
Edit: This can be done even without adding a new(count) attribute. Instead of passing the this.attributes.count.value to the two price functions, you can do:
$('input').change(function () {
discountPrice($(this).parent().prevAll().length);
});
FIDDLE2

Categories

Resources