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

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.

Related

Verify inside input if value is over max

I have a data table that I render in ASP.NET MVC using C# in a razor view.
To make a really short example of what I'm trying to achieve let's use this table as an example.
function setValueAttr(el) {
el.setAttribute('value', el.value)
}
function aplicar() {
var myTab = document.querySelectorAll('#tableID tbody tr .txtID:not([value=""])');
var tableData = [];
Array.from(myTab).forEach(input => {
var tds = input.closest('tr').children;
var obj = {};
obj.A = tds[0].textContent;
obj.B = tds[1].textContent;
obj.C = tds[2].textContent;
obj.D = tds[3].textContent;
obj.E = input.value;
tableData.push(obj);
});
console.log(tableData);
}
<table class="table table-bordered" width="100%" cellspacing="0" id="tableID">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
</thead>
<tbody>
<tr>
<td align="center">val1</td>
<td align="center">val2</td>
<td align="center">val3</td>
<td align="center">1500</td>
<td align="center" class="myID"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" value="" min="0" max="1000"></td>
</tr>
<tr>
<td align="center">val1</td>
<td align="center">val2</td>
<td align="center">val3</td>
<td align="center">1500</td>
<td align="center" class="myID"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" value="" min="0" max="1000"></td>
</tr>
<tr>
<td align="center">val1</td>
<td align="center">val2</td>
<td align="center">val3</td>
<td align="center">1500</td>
<td align="center" class="myID"><input type="number" name="txtID" class="txtID" oninput="setValueAttr(this)" value="" min="0" max="1000"></td>
</tr>
</tbody>
</table>
<form>
<button type="button" onclick="aplicar()">Aplicar</button>
</form>
What this does is that it will pull data out of the rows that do have data inside the last input in the column E into an array
However I can input any amount of data even if I setup the attribute max="1000" on all of my inputs, how I can solve this?
In the MVC view instead of the static max value I have on this example I have a foreach for a data table that I get from a dataset, declaring it inside as #my_value will output different values inside the max="" attribute however this won't stop me from writing any value just like in this example
You can add a simple addition to your script function to check for max. I think unless you use observers you will have to check in your javasctipt
function aplicar() {
var myTab = document.querySelectorAll('#tableID tbody tr .txtID:not([value=""])');
var tableData = [];
Array.from(myTab).forEach(input => {
var tds = input.closest('tr').children;
var obj = {};
obj.A = tds[0].textContent;
obj.B = tds[1].textContent;
obj.C = tds[2].textContent;
obj.D = tds[3].textContent;
if(input.value > MAX)
{
input.value = MAX;
}
obj.E = input.value;
tableData.push(obj);
});
console.log(tableData);
}
Setting the attribute value with javascript is most likely circumventing the validation mechanism of the input element. Why do you set the value element using javascript? The value attribute is filled by typing a value into the input element by itself.
Added this attribute
var myTab = document.querySelectorAll('#tableID tbody tr .txtID:not([value=""]):valid');
And it fixed it, thanks a lot everyone, specially #HereticMonkey who solved the issue

Why won't my javascript function pick up my input texts when looping through table?

My function will succesfully load the dropdown values but fails to load any of the input text values. I just get an output showing blank input boxes so it's not picking up what type of input it is.
$(document).ready(function () {
$('#clicker').on('click', function (e) {
var tableToObj = function (table) {
var trs = table.rows, //replacing , with ; at end of each line
trl = trs.length,
i = 0,
j = 0,
keys = [],
obj, ret = [];
for (; i < trl; i++) {
if (i === 0) {
// var sel = $(trs[i].children[j]).find('select');
//changed from input
for (; j < trs[i].children.length; j++) { //removed ; from (;
var sel = $(trs[i].children[j]).find('select'); //same as below
if (sel.length === 0) {
keys.push(trs[i].children[j].innerHTML);
} else {
keys.push(sel.find('option:selected').val());
}
var input = trs[i].children[j].value;
}
} else {
obj = {};
for (j = 0; j < trs[i].children.length; j++) { //this works j = 0;
var sel = $(trs[i].children[j]).find('select'); //replaced " with ' around select
if (sel.length === 0) {
obj[keys[j]] = trs[i].children[j].innerHTML;
} else {
obj[keys[j]] = sel.find('option:selected').val();
}
var input = trs[i].children[j].value;
}
ret.push(obj);
}
}
return ret;
};
document.getElementById('r').innerHTML = JSON.stringify(tableToObj(document.getElementById('myTable')));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>FirstColumn</th>
<th>SecondColumn</th>
<th>ThirdColumn</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option><option value="tr4">tr4</option></select></td>
<td>1</td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option></select></td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option><option value="tr4">tr4</option></select></td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option></select></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>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option></select></td>
</tr>
</tbody>
</table>​​<input type="button" id="clicker" value="Click Me"/>
<br/> Result:
<fieldset id="r">
</fieldset>
<div class="ms-rtestate-read ms-rte-wpbox" contenteditable="false" unselectable="on">
<div class="ms-rtestate-notify ms-rtestate-read 9622406d-82bb-4b09-8e13-8fb81e9da538" id="div_9622406d-82bb-4b09-8e13-8fb81e9da538" unselectable="on">
</div>
<div id="vid_9622406d-82bb-4b09-8e13-8fb81e9da538" unselectable="on" style="display: none;">
</div>
</div>​<br/>
My current OBJ output is:
[{"FirstColumn":"tr1","SecondColumn":"1","ThirdColumn":"tr1"},{"FirstColumn":"1","SecondColumn":"2","ThirdColumn":"tr1"},{"FirstColumn":"","SecondColumn":"","ThirdColumn":"tr1"},{"FirstColumn":"\n ","SecondColumn":"","ThirdColumn":""},{"FirstColumn":"","SecondColumn":"","ThirdColumn":"tr1"}]

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();

How to get sum of onload inputs

HTML:
<table id="tab1">
<tr id="maint">
<td style="background-color:white;"></td>
<td>słowo klucz</td>
<td>ilość wynikow google</td>
</tr>
<tr>
<td id="maint">słowo klucz</td>
<td><input type="text" name="klucz" value="" required></td>
<td><input type="number" name="wyszkiwania" value="" onblur="sumX()" onkeyup="operatorf()" id="eq"required></td>
</tr>
<tr>
<td id="maint">słowo klucz</td>
<td><input type="text" name="klucz" value=""></td>
<td><input type="number" name="wyszkiwania" value="" onblur="sumX()" onkeyup="operatorf()" id="eq"required></td>
</tr>
</table>
JS:
var wejscie = document.getElementById('eq').value;
if ( wejscie <= 100000) {
var stawka13 = 59;
var stawka46 = stawka13*0.75;
var stawka710 = stawka46*0.55;
}
else {
var stawka13 = wejscie/100000*59;
if (stawka13 > 210) {
stawka13 = 210;
}
var stawka46 = stawka13*0.75;
var stawka710 = stawka46*0.55;
}
stawka13 = Math.round(stawka13).toFixed(2);
stawka46 = Math.round(stawka46).toFixed(2);
stawka710 = Math.round(stawka710).toFixed(2);
document.getElementById('sum13').innerHTML = "";
document.getElementById('sum46').innerHTML = "";
document.getElementById('sum710').innerHTML = "";
document.getElementById('sum13').innerHTML = " "+sum13+" zł";
document.getElementById('sum46').innerHTML = " "+sum46+" zł";
document.getElementById('sum710').innerHTML = " "+sum710+" zł";
I would like to get an sum of it but with this eq.
I try arr etc but aint work "properly" as I want.
My target is just sum all of it with all math in it.
I'm not allowed to add jq to it so it is impotant to stay on meta.

jquery: Summing values after dynamic delete of content gets NaN

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));
}

Categories

Resources