Multiply results using same function displayed on same page - javascript

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

Related

Duplicate all Column Cell Input Values with first Column Cell input value

I have an html table that is wrapped by a form with each cell having an input element in it.
I was wondering if there is a way to obtain the first cell's input value of a particular column and pasting that value in the rest of the cells in that column. In other words, the user will type into the input field of first cell and then click on button to duplicate that entry into the rest of the cells of that column.
Assuming you have a table with a button on each row, give the button a class so that it can have an event assigned:
<button type='button' class='copybtn'>copy</button>
don't use IDs as you need multiple buttons;
$(".copybtn").click(function() {
You can get the button's column using var col = $(this).closest("td").index() (add 1 as .index() is 0-based, but we need 1-based :nth-child).
Get the column cells using:
var cells = $("table").find("tr > td:nth-child(" + col + ")");
Various ways to handle this - eg get all the cells as above, then get the first for the input and last for the button or get the input from the first row's nth-child (as in the snippet)
To get the value: var val = inp.val()
To copy the values, depends on your HTML, you could give each destination cell a class then:
cells.find("td.dest").text(val);
or you can get all cells and exclude first/last:
tbl.find("tr:not(:first):not(:last) > td:nth-child(" + col + ")").text(val);
Altogether:
$(".copybtn").click(function() {
// get 0-based column index
var col = $(this).closest("td").index() + 1;
var tbl = $(this).closest("table");
var val = tbl.find("tr:first td:nth-child(" + col + ")").find("input").val();
tbl.find("tr:not(:first):not(:last) > td:nth-child(" + col + ")").text(val);
});
input {
width: 50px;
}
td {
min-width: 20px;
border: 1px solid #CCC;
margin: 0;
padding: 5px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='t'>
<tbody>
<tr>
<td><input type='text' class='inp' /></td>
<td><input type='text' class='inp' /></td>
<td><input type='text' class='inp' /></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td><button type='button' class='copybtn'>copy</button></td>
<td><button type='button' class='copybtn'>copy</button></td>
<td><button type='button' class='copybtn'>copy</button></td>
</tr>
</tbody>
</table>
If I understand correctly, you'll need something like this:
const copy=(id) => {
var value = document.getElementById("col"+id+"-input").value
var list = document.getElementsByClassName("col"+id+"-input")
for (i = 0; i < list.length; i++)
list[i].value = value
}
document.getElementById("col1-button").addEventListener("click", ()=>copy(1))
document.getElementById("col2-button").addEventListener("click", ()=>copy(2))
document.getElementById("col3-button").addEventListener("click", ()=>copy(3))
<table>
<tr>
<td><input id="col1-input" class="col1-input"><button id="col1-button">OK</button><br>
<td><input class="col1-input"></td>
<td><input class="col1-input"></td>
<td><input class="col1-input"></td>
<td><input class="col1-input"></td>
</tr>
<tr>
<td><input id="col2-input" class="col2-input"><button id="col2-button">OK</button><br>
<td><input class="col2-input"></td>
<td><input class="col2-input"></td>
<td><input class="col2-input"></td>
<td><input class="col2-input"></td>
</tr>
<tr>
<td><input id="col3-input" class="col3-input"><button id="col3-button">OK</button><br>
<td><input class="col3-input"></td>
<td><input class="col3-input"></td>
<td><input class="col3-input"></td>
<td><input class="col3-input"></td>
</tr>
</table>
Try this... JQuery solution.
Good luck!
$(function() {
$('button').on('click', function() {
var inputVal = $(this).prev().val();
// Plus one because arrays start at zero
var colIndex = $(this).parent().parent().children().index($(this).parent()) + 1;
$('table tr td:nth-child('+colIndex+')').not(':first')
.html(inputVal);
});
});
body { margin: 10px; }
table { max-width: 600px; }
td { min-width: 280px; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="">
<table class="table table-bordered">
<tr>
<td><input type="text"><button type="button">Copy</button></td>
<td><input type="text"><button type="button">Copy</button></td>
<td><input type="text"><button type="button">Copy</button></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</form>

How to access HTML array object in javascript?

sorry for asking simple question. I am really a beginner in Javascript. I need to access my HTML array form object in my javascript, but I don't know how to do it.
The goal is to trigger the alert in javascript so the browser will display message according to the condition in javascript. Here is my code :
checkScore = function()
{
//I don't know how to access array in HTML Form, so I just pretend it like this :
var student = document.getElementByName('row[i][student]').value;
var math = document.getElementByName('row[i][math]').value;
var physics = document.getElementByName('row[i][physics]').value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
student_score.row[i][otherinfo].focus();
student_score.row[i][otherinfo].select();
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
<p>If you click the "Submit" button, it will save the data.</p>
We are going to leverage few things here to streamline this.
The first is Event Listeners, this removes all javascript from your HTML. It also keeps it more dynamic and easier to refactor if the table ends up having rows added to it via javascript.
Next is parentNode, which we use to find the tr that enclosed the element that was clicked;
Then we use querySelectorAll with an attribute selector to get our target fields from the tr above.
/*This does the work*/
function checkScore(event) {
//Get the element that triggered the blur
var element = event.target;
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var otherField = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math, 10) >= 80) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics, 10) >= 80) {
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
/*Wire Up the event listener*/
var targetElements = document.querySelectorAll("input[name*='math'], input[name*='physics']");
for (var i = 0; i < targetElements.length; i++) {
targetElements[i].addEventListener("blur", checkScore);
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<tr>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]" class='student'></td>
<td><input type="number" name="row[1][math]" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
Well, it follows your line of code exactly as it is (because you said you do not want to change the code too much).
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
JavaScript [Edited again using part of the #Jon P code, the query selector is realy more dynamic, and the value of the "other" field you requested is commented out]
//pass element to function, in html, only add [this] in parenteses
checkScore = function (element) {
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var other = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math) >= 80) {
//other.value = student + " ,You are good at mathematic";
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80) {
//other.value = student + " ,You are good at physics";
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
Tested :), and sorry about my english!
Try that, haven't tested it
var form = document.getElementsByName("student_score")[0];
var students = form.getElementsByTagName("tr");
for(var i = 0; i < students.length; i++){
var student = students[i].childnodes[0].value;
var math = students[i].childnodes[1].value;
var physics = students[i].childnodes[2].value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
}

Obtain location of input within table cell HTML

I have a a table with inputs inside each table cell like so:
<table width="300" border="1" align="center" id="mainTable">
<tr>
<td><input onkeyup="insertToArray(value)" size="1" maxlength="1" /></td>
<td><input onkeyup="insertToArray(value)" size="1" maxlength="1" /></td>
<td><input onkeyup="insertToArray(value)" size="1" maxlength="1" /></td>
<td><input onkeyup="insertToArray(value)" size="1" maxlength="1" /></td>
</tr>
</table>
I would like to know how to obtain the location (row and column) of an input within the table (using javascript). I know how to do it for a regular cell with nothing inside, but for an input within the cell I can't seem to find a way. The function inside the input is for another purpose.
Modify the call to the function insertToArray(value) to insertToArray(this) and then inside the function do
function insertToArray(elem){
...
var tdElem = elem.parentNode;
var trElem = tdElem.parentNode;
console.log("Row: " + trElem.rowIndex);
console.log("Column: " + tdElem.cellIndex);
...
}
If you are able to get a reference to the table cell, then you just have to get access to the children inside of that node.
You can use `childNodes' which returns a NodeList object and then you use the index to access the children so in your case, the input box.
example:
document.getElementById("firstTableCell").childNodes[0].value;
I adopted the following approach, though it uses the keyup listener from jquery:
HTML:
<table width="300" border="1" align="center" id="mainTable">
<tr>
<td><input size="1" maxlength="1" /></td>
<td><input size="1" maxlength="1" /></td>
<td><input size="1" maxlength="1" /></td>
<td><input size="1" maxlength="1" /></td>
</tr>
<tr>
<td><input size="1" maxlength="1" /></td>
<td><input size="1" maxlength="1" /></td>
<td><input size="1" maxlength="1" /></td>
<td><input size="1" maxlength="1" /></td>
</tr>
</table>
JS:
$("#mainTable input").keyup(function() {
var colIndex = $(this).parent()[0].cellIndex;
var rowIndex = $(this).parent()[0].parentElement.rowIndex;
})
Hope this helps!
It can be done in different ways, the code I included here is just to help you understand it better and depending on what you want to do, this is a nice easy approach to your issue. You can get the indexes instead, again, it depends on what you want to do.
HTML:
<table width="300" border="1" align="center" id="mainTable">
<tr class="row1">
<td><input class="tableCell" id="cell1" size="1" maxlength="1" /></td>
<td><input class="tableCell" id="cell2" size="1" maxlength="1" /></td>
<td><input class="tableCell" id="cell3" size="1" maxlength="1" /></td>
<td><input class="tableCell" id="cell4" size="1" maxlength="1" /></td>
</tr>
</table>
JS
window.onload = function() {
var cells = document.getElementsByClassName("tableCell");
for (var x = 0; x < cells.length; x++) {
cells[x].addEventListener("keyup", function(e) {
// get row class name:
var rowClass = (e.target).parentElement.parentElement.className;
alert("Row classname: " + rowClass);
// get the value insede the cell:
var cellValue = (e.target).value;
alert("Value entered: " + cellValue);
var cellId = e.target.id;
alert("Cell ID: " + cellId);
});
}
You could use a utility method that to looks for the closest parent
using a tag name:
Here's an example
function getClosestParent( needle, haystack ) {
var parent = null;
var target = needle.toUpperCase();
var element = haystack.parentElement;
while ( parent == null ) {
if ( element !== null ) {
if ( element.tagName === target ) {
parent = element;
}
}
else {
break;
}
element = element.parentElement;
}
return parent;
}
document.querySelector("input").addEventListener("click", function() {
var row = getClosestParent("tr", this)
var column = getClosestParent("td", this)
alert(row);
alert(column);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="300" border="1" align="center" id="mainTable">
<tr>
<td><input onkeyup="insertToArray(value)" size="1" maxlength="1" /></td>
</tr>
</table>
I've figured out a great way to do it.
I have 2 global variables representing the column and the row objects (tr, td)
function returnParent(x)
{
parentOfInput = x.parentNode; //td level
parentOfTd = parentOfInput.parentNode; //tr level
}
And I call this function alongside the other as well like so (note that I call returnParent() first since I want the position first thing when I enter something in input):
<table width="300" border="1" align="center" id="mainTable">
<tr>
<td><input onkeyup="returnParent(this); insertToArray(value);" size="1" maxlength="1" /></td>
<td><input onkeyup="returnParent(this); insertToArray(value);" size="1" maxlength="1" /></td>
<td><input onkeyup="returnParent(this); insertToArray(value);" size="1" maxlength="1" /></td>
<td><input onkeyup="returnParent(this); insertToArray(value);" size="1" maxlength="1" /></td>
Finally in my insertToArray(value) function, I get the column and row like so:
function insertToArray(value)
{
var a = value;
//get the cell position using parentNode
tableCol = parentOfInput.cellIndex;
tableRow = parentOfTd.rowIndex;
}

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

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