Calculate using elements' contents in jQuery - javascript

I want to run a calculation using the text of related elements (mcost_el=mcount_el*mprice_el) and write the result to the text of another element (to "mcost_el").
<tr>
<td class="mcount_el">2</td>
<td class="mprice_el">544,33</td>
<td class="mcost_el">0</td>
</tr>
<tr>
<td class="mcount_el">3,9</td>
<td class="mprice_el">460,00</td>
<td class="mcost_el">0</td>
</tr>
I write this code:
var count=0;
var price=0;
$('.mcost_el').each(function(){
count=parseInt($('.mcount_el').each.text().replace(",","."));
price=parseInt($('.mprice_el').each.text().replace(",","."));
$('.mcost_el').html(parseFloat(count)*parseFloat(price));
});
but it don't work.

Something like this:
$('tr').each(function(){
var count=parseFloat($('.mcount_el',this).text().replace(",","."));
var price=parseFloat($('.mprice_el',this).text().replace(",","."));
$('.mcost_el', this).html(count*price);
});
Live example: http://jsfiddle.net/BzVyc/
The difference is that, instead of doing a parseInt on the string then a parseFloat on the resulting int, you just do a parseFloat on the string.

You need something like this -
var count=0;
var price=0;
$('tr').each(function(){
count=parseFloat($(this).find('td.mcount_el').text().replace(",","."));
price=parseFloat($(this).find('td.mprice_el').text().replace(",","."));
$(this).find('td.mcost_el').html(count*price);
});
Which will -
Loop through each table row
For the current table row, find the count and price variables by
extracting them from the <td> relevant to the current row using $(this).find('td.<classname>') syntax
Multiply the two variables and and add the result to the total <td>
Working demo - http://jsfiddle.net/ipr101/AVGgU/1

maybe something along the line of
elements = $("body").children().length
have a look, length

$("#table_id tr").each(function() {
var count = parseInt($(this).find(".mcount_el").text());
var price = parseFloat($(this).find(".mprice_el").text());
var cost = count * price;
$(this).find(".mcost_el").text(cost.toFixed(2));
});

Related

How to iterate through table tr and get the value for first td? JavaScript

I have the function where I want to get the value for first td in each table row. While looping I want to compare each of these values with the date value that user picked. After comparing the dates I need to get the position where that value should be placed in the table. Here is example of my code:
HTML Table:
<table id="tblBody_DBA">
<tbody>
<tr id="Att_5258717">
<td>03/28/2017</td>
<td></td>
</tr>
<tr id="Att_5258339">
<td>03/25/2017</td>
<td>03/26/2017</td>
</tr>
<tr id="Att_5258337">
<td>03/22/2017</td>
<td>03/24/2017</td>
</tr>
<tr id="Att_5258332">
<td>03/16/2017</td>
<td>03/21/2017</td>
</tr>
<tr id="Att_5258331">
<td>03/10/2017</td>
<td>03/15/2017</td>
</tr>
</tbody>
</table>
function sortRow(distType, rowId){
var newVal = document.getElementById("newDate").value; //this is new value that I have to compare against existing values and return position in the table.
var tblID = document.getElementById("parentTable").value;
var table = window.parent.document.getElementById("tblBody_"+tblID);
var arrayDates = [];
for(var i=0; table.rows.length; i++){
//Here I'm getting JavaScript error: TypeError: table.rows[i] is undefined
alert(table.rows[i].cells[0].innerHTML);
}
}
I'm getting value for each table cell in alert box but on the end error shows in my debugger. If anyone can help please let me know. I'm not able to use JQuery, plain JavaScript is the only way to et this done in my case.
You can just grab the first td from each tr specifically:
var table = document.getElementById('tblBody_DBA');
var targetTDs = table.querySelectorAll('tr > td:first-child');
for (var i = 0; i < targetTDs.length; i++) {
var td = targetTDs[i];
console.log(td.innerHTML);
}
First you get all of the tr elements using var allTr = document.querySelectorAll ('tr')
Then you loop through them and get the text from the first td
for (var i = 0; i < allTr.length; i++) {
allTr [i].firstChild.innerHTML;
}
<table id="tblBody_DBA">
<tbody>
<tr id="Att_5258717">
<td>03/28/2017</td>
<td></td>
</tr>
<tr id="Att_5258339">
<td>03/25/2017</td>
<td>03/26/2017</td>
</tr>
<tr id="Att_5258337">
<td>03/22/2017</td>
<td>03/24/2017</td>
</tr>
<tr id="Att_5258332">
<td>03/16/2017</td>
<td>03/21/2017</td>
</tr>
<tr id="Att_5258331">
<td>03/10/2017</td>
<td>03/15/2017</td>
</tr>
</tbody>
</table>
<script>
function sortRow(distType){
var table = document.getElementById(distType); //this is new value that I have to compare against existing values and return position in the table.
for (var i = 0; i < table.rows.length; i++) {
var firstCol = table.rows[i].cells[0]; //first column
console.log(firstCol.innerHTML);// or anything you want to do with first col
}
}
sortRow("tblBody_DBA");
</script>​
The main issue is in the for loop's end condition. You did not provide a comparison with i and so it was continuing beyond the last row of the table, producing the error you got.
To find the row for which the input date falls between the dates in the first and second column, you'll need to convert those values to dates and then do a comparison:
// Parse text as date and convert to an absolute day number
newVal = Math.floor(Date.parse(newVal) / 24*60*60*1000);
for(var i=0; i < table.rows.length; i++){
// Do the same conversion for the table texts
var start = Math.floor(Date.parse(table.rows[i].cells[0].textContent) / 24*60*60*1000);
var end = Math.floor(Date.parse(table.rows[i].cells[1].textContent) / 24*60*60*1000);
// Make the comparison
if (start <= newVal && (newVal <= end || isNaN(end))) {
return i; // the row where the range for that value was found
}
}
Possible reasons for error could be :
document.getElementById("parentTable").value will be returning a value which will not map to any table id when using in window.parent.document.getElementById("tblBody_"+tblID);
There are no rows in the table which has been returned by window.parent.document.getElementById("tblBody_"+tblID);
Also you havn't provided terminating condition in your for loop, which should be like : for(var i=0; i < table.rows.length; i++)
One more thing why you are using window.parent when getting the table. If your table and rest of the content are in same page then you can get table by simply calling document.getElementById("tblBody_"+tblID);. If you creating multi frame page then this will be required but this will get the table from the parent window of window in which you have function sortRow defined.
Forgot to paste this snippet, which might help. Until you answer the questions on the comment, there's no way to determine the best approach.
Note: The following code uses some ES6 syntax, which may not be available in IE as #Brian has pointed out. For that reason, Babel.js or a suitable Polyfill is encouraged.
The idea is to grab the first-child cell of each row and iterate over them. Using map you can return an array, which can then be sorted, or queried using indexOf.
By returning the element as the first item of the array, you can use [0].parentNode to retrieve the TR, or [0].parentNode.id to get it's ID.
"use strict";
let newVal = document.getElementById('newDate').value;
console.log('newVal:', new Date(newVal));
let tbl = document.getElementById('tblBody_DBA');
var col_values = [...tbl.querySelectorAll('tr > td:first-child')].map(el => {
return [el, el.textContent, +new Date(el.textContent)];
}).sort((a,b) => a[2] > b[2] ? -1 : 1);
console.log(col_values);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<p>I have the function where I want to get the value for first td in each table row. While looping I want to compare each of these values with the date value that user picked. After comparing the dates I need to get the position where that value should be
placed in the table. Here is example of my code:</p>
<p>HTML Table:</p>
<input id="newDate" value='3/24/2017' type="hidden" />
<table id="tblBody_DBA" class="table table-striped">
<tbody>
<tr id="Att_5258717">
<td>03/28/2017</td>
<td></td>
</tr>
<tr id="Att_5258339">
<td>03/25/2017</td>
<td>03/26/2017</td>
</tr>
<tr id="Att_5258337">
<td>03/22/2017</td>
<td>03/24/2017</td>
</tr>
<tr id="Att_5258332">
<td>03/16/2017</td>
<td>03/21/2017</td>
</tr>
<tr id="Att_5258331">
<td>03/10/2017</td>
<td>03/15/2017</td>
</tr>
</tbody>
</table>
<p>
I'm getting value for each table cell in alert box but on the end error shows in my debugger. If anyone can help please let me know. I'm not able to use JQuery, plain JavaScript is the only way to et this done in my case.</p>

How to automatically call a JavaScript that modify a value before show this value?

I am very new in JavaScript and I have the following problem to solve.
I have a table that contains this td cell:
<td class= "dateToConvert" width = "8.33%">
<%=salDettaglio.getDataCreazione() != null ? salDettaglio.getDataCreazione() : "" %>
</td>
This retrieve a String from an object and show it into the cell
The problem is the retrieved string represent a date having the following horrible form: 20131204 and I have to convert it into the following form: 2013-12-04.
So I am thinking to create a JavaScript that do this work when the value is retrieved.
My problem is: how can I do to automatically call the JavaScript before to show the value into the td cell? (So I show the modified output in the desidered form)
EDIT 1:
So I have create thid JavaScript function into my page:
function convertData() {
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.innerText = td.innerText.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
}
But it don't work because it never enter in this function (I see it using FireBug JavaScript debugger). Why? What am I missing? Maybe have I to call it explicitly in some way in my td cell?
Of course it is better to fix backend method to make it return proper format. But since you have no control over it try to use something like this:
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.textContent = td.textContent.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
Check the demo below.
var tds = document.querySelectorAll('.dateToConvert');
[].slice.call(tds).forEach(function(td) {
td.textContent = td.textContent.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3');
});
<table>
<tr>
<td class= "dateToConvert" width = "8.33%">
20131204
</td>
<td class= "dateToConvert" width = "8.33%">
20140408
</td>
</tr>
</table>

jQuery change number inside a name attribute

I'm writing some JavaScript to clone a table row containing form elements.
It's working well so far but there's one piece I can't quite figure out.
The element names have a number which increases with every row.
E.g:
<table>
<tbody>
<tr>
<td><input type="text" name="name[0][abc]" /></td>
<td><button class="add-row-button">+</button></td>
</tr>
<tr>
<td><input type="text" name="name[1][abc]" /></td>
<td><button class="add-row-button">+</button></td>
</tr>
</tbody>
</table>
I need the cloned row to update the number. There are multiple fields in each row which need this updated number so I can't just include the new name in the jQuery code. What I think has to happen is I need get the name, use a regex replace, then update the attribute.
Here's my current (simplified for the example) jQuery:
// Current num of elements. Names are 0 based so this will be the number used
// for the new name.
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Set the new field selector.
var $newRow = $(this).closest('tr').next();
$newRow.find('input[type="text"]').val('');
formRowCount++;
});
Can someone point me in the right direction. Before formRowCount++; I need to get the current element name and update the number with formRowCount.
Yeah, you can use regex if you want.
var formRowCount = $('table tr').length;
$('.add-row-button').click(function() {
// Clone the last row and insert it.
$(this).closest('tr').last().clone().insertAfter($(this).closest('tr'));
// Select the input field
var $newInput = $(this).closest('tr').next().find('input[type="text"]');
// Update the input value and name attribute
var newName = $newInput.attr('name').replace(/^(name\[)\d+(\].+)$/, '$1' + formRowCount + '$2');
$newInput.val('').attr('name', newName);
// Update the number
formRowCount++;
});

Is it possible to get the value of a <td> element using onclick?

I currently have a table that has a list of email template names being echoed using php. Below is part of the php code. I'm trying to grab the table value and pass it to my JS file where a future AJAX command will pass it to a different file (that I won't have any issues with). My first attempt to alert out the value stated that the value was undefined. My second attempt showed the type of element it was inside (at the time it was a span). Now it's not showing anything. Suggestions?
PHP code:
<table class="departments">
<tr>
<th scope="col" style="width: 175px;">Email Name</th>
';
$get_depts = mysql_query("SELECT dept_name FROM depts where bus_id = '{$_SESSION['bus_id']}'");
while(($department = mysql_fetch_assoc($get_depts)))
{
echo '
<th scope="col" style="width: 175px;">'.$department['dept_name'].'</th>
';
}
echo '
</tr>
';
$get_emails = mysql_query("SELECT id, email_name from emails where bus_id = '{$_SESSION['bus_id']}' ORDER BY email_name ASC");
while(($email = mysql_fetch_assoc($get_emails)))
{
echo '
<tr>
<td id="test" onclick="moveValue()">'.$email['email_name'].'</td>
';
Current JS code:
function moveValue()
{
var x = document.getElementById(test);
var y = x.innerHTML;
alert(y);
}
Javascript:
var y = document.getElementById("test").innerText;
jQuery:
$("#test").text();
To get the HTML:
var html = document.getElementById("test" ).innerHTML;
jQuery:
$("#test").html();
You id attribute would be the same for every td inside the loop. So JS would not know which element you want.
You could try passing this into the onclick method
HTML
<td onclick="moveValue(this);">
JS
function moveValue( elem )
{
alert(elem.innerHtml);
}
I would take a look at jQuery if I were you. It makes all this stuff much easier to achieve.
I don't want to get into all the problems with your code as there are rather a lot. However, getting the value of a <td> element by clicking is trivial to achieve.
You first need to assign a click handler to each cell in your table. The easiest way to do this is to loop through each cell and assign the handler like so:-
var cells = document.getElementsByTagName('td');
for(var i = 0; i <= cells.length; i++){
cells[i].addEventListener('click', clickHandler);
}
function clickHandler()
{
alert(this.textContent);
}
Then every time you click on a cell the clickHandler() will be called and you can run whatever code you wish.
You can see it working in this fiddle
Lots of information here https://developer.mozilla.org/en-US/docs/Web/API
With javascript:
To get raw text without any elements or:
somevar=document.getElementById ( "test" ).innerText;
To get full html code of tag. Contents will be stored in 'somevar' variable.
somevar=document.getElementById ( "test" ).innerHTML;
You can do it either by
function moveValue()
{
var x = document.getElementById('test');
var y = x.innerHTML;
alert(y);
}
or by:
function moveValue(element) {
var y = element.innerHTML;
alert(y);
}
//with the following html code:
<td onclick="moveValue(this)">'.$email['email_name'].'</td>
its work.
function clickValue(elem) {
var x = document.getElementById(elem).innerHTML;
alert(x);
}
<table>
<th>Coba</th>
<tr>
<td id="1" onclick="clickValue('1')">value</td>
</tr>
<tr>
<td id="2" onclick="clickValue('2')">value yg ke 2</td>
</tr>
</table>
Change id="*anyvalue*" and clickValue('*anyvalue*')

populate div by doing math on table cells

Trying to figure this stuff here out. Can't figure out if it's on the count of me having the numbers in the tds already. Is it takin em in as strings so it don't know how to do the math? I know I got this all wrong, but this is easy stuff I reckon so I hope you can set me straight. Much obliged.
<table id="Table">
<tr>
<td width="124" style="position: relative" rowspan="4">
<div id="percentage"></div>
</td>
<td>Total</td>
<td id="Total">259</td>
<td>Result</td>
<td id="Count">11</td>
</tr>
</table>
JS:
var total = $("Total");
var count = $("Count");
var Result = (Count/Total*100);
document.getElementById("percentage").innerHTML = Result;
That didn't work.
Also I need that there Result in .innerHTML to come out as a percentage. Should I just multiply it by 100 like I did here and attach a "%" manually?
Your JavaScript is looking for element types instead of the id's change your js to:
var total = parseInt($("#Total").text(), 10);
var count = parseInt($("#Count").text(), 10);
var Result = (count/total*100);
You are also not converting to a number.
you forget '#' to select by Id and you are not convert to int, so you can make it by jQuery in one line:
$('#percentage').text(parseInt($('#Count').text())/parseInt($('#Total').text())*100);

Categories

Resources