The function is working correctly if simply var x (a digit)
but when I am trying to apply the same to html table class by name it is not working at all
<html>
<body>
<tr>
<td class="sal">45.515420</td>
</tr>
<script>
function myFunction() {
var sal = document.getElementsByClassName("sal");
for (i = 0; i < sal.length; i++) {
var currentValue = sal[i].innerHTML;
var newvalue = (sal.toFixed(2));
sal[i].innerHTML = newValue
}
}
onload = myFunction()
</script>
</body>
</html>
The provided code needs some changes, I'll try to address them:
Convert currentValue to number because toFixed is part of a Number
var currentValue = Number(sal[i].innerHTML);
onload = myFunction(), we can just call the function to run it on load
myFunction();
Wrapped <td class='sal'>45.515420</td> in a <table> to make the HTML valid
<table>
<tr>
<td class='sal'>45.515420</td>
</tr>
</table>
Applying those fixes gives:
function myFunction() {
var sal = document.getElementsByClassName("sal");
for (i = 0; i < sal.length; i++) {
var currentValue = Number(sal[i].innerHTML);
sal[i].innerHTML = currentValue.toFixed(2);
}
}
myFunction();
<table>
<tr>
<td class='sal'>45.515420</td>
</tr>
</table>
First, in order to use document.getElementsByClassName on td elements, you need to wrap your tr and td element inside table tag.
Second, toFixed() is a method for number and you need to convert the string to a number using Number() before you use toFixed().
var sal = document.getElementsByClassName("sal");
for (i = 0; i < sal.length; i++) {
var currentValue = sal[i].innerHTML;
var newValue = Number(currentValue).toFixed(2);
sal[i].innerHTML = newValue;
}
<html>
<body>
<table>
<tbody>
<tr>
<td class="sal">45.515420</td>
<td class="sal">49.515420</td>
</tr>
</tbody>
</table>
</body>
</html>
Along with all the other good advice, here's version that uses more modern JS practices.
querySelectorAll
forEach
Arrow function expressions
const sals = document.querySelectorAll('.sal');
sals.forEach(sal => {
const number = Number.parseFloat(sal.textContent);
sal.textContent = number.toFixed(2)
});
<table>
<tbody>
<tr>
<td class="sal">45.515420</td>
</tr>
</tbody>
</table>
Related
I have a table like this in my page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<input type="text" id="myInput" placeholder="Search for anything.." title="Type in a name" ></input>
<table class="table table-bordered table-striped" >
<tbody id="myTable">
<td>
<?php echo $product_name ?>
</td>
<td>
<?php echo $gender ?>
</td>
<td>
<?php echo $date ?>
</td>
</td>
<td>
<?php echo $quantity ?>
</td>
<td>
<?php echo $shopname ?>
</td>
<td class="valor text-right">
<?php echo $price ?>
</td>
</tbody>
<tfoot>
<tr class="info">
<td colspan="2" class="text-right">TOTAL:</td>
<td class="total text-right"></td>
</tr>
</tfoot>
</table>
The idea here is to calculate the total for the column with class valor and it's shown on foot of the table at the colmn with class total.
And also the idea is that the user can filter rows typing anything on the input text named myInput and therefore the total should be recalculated.
By this time I'm able to filter rows with the jQuery code below:
$(document).ready(function () {
var $rows = $(".table tbody tr");
var total = 0;
$rows.each(function () {
total += parseFloat($(this).find(".valor").text().replace(/\./g, "").replace(",", "."));
});
$("#myInput").keyup(function () {
var filtertext = $(this).val();
var regex = new RegExp(filtertext, 'i');
$rows.hide().filter(function () {
return regex.test($(this).text());
}).show();
$(".table tbody tr:visible").each(function () {
total += parseFloat($(this).find(".valor").text().replace(/\./g, "").replace(",", "."));
});
$(".total").html(formataTotal(total.toFixed(2)));
});
$(".total").html(formataTotal(total.toFixed(2)));
});
function formatTotal(num) {
var parts = num.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
return parts.join(",");
}
By using the above code m successfully filtering the rows but i am not getting any sum of the column after being filtered rows nor the total sum of that column valor
A couple things to address to get the script functioning
You have defined formatTotal but you are calling formataTotal.
With that adjustment you should start seeing a total output.
You'll see a total but you now have a running total since you
have the variable total was defined in the global scope of the
script. This will persist until you refresh the browser. Reset your total when your keyup function begins.
$("#myInput").keyup(function () {
total = 0;
...
I would recommend to also break some of your code into smaller, reuseable functions. For example, when setting your total value create a function as such
function displayTotal(total) {
$(".total").html(formatTotal(total.toFixed(2)));
}
You can take that one step further and note that you use the same class consistently to output the total so you might want to offload that a global.
$totalElement = $(".total");
function displayTotal(total) {
$totalElement.html(formatTotal(total.toFixed(2)));
}
You should consider handling your total value consistently and with some precaution so you do not end up with a 'NaN' value. Again you can break the task of checking a row for a price with a function.
function getPriceForRow(row) {
$valor = $(row).find(".valor");
if($valor.length) {
return parseFloat($valor.text().replace(/\./g, "").replace(",", "."));
}
return parseFloat(0);
}
With a couple small adjustments your script may look as such. There are other improvements that can be made and things that you should ideally do in this case, but hopefully I gave a sense for what you can accomplish just with breaking your code down into solid functions.
$(document).ready(function () {
var $rows = $(".table tbody tr");
var $totalElement = $(".total");
var total = 0;
$rows.each(function () {
total += getPriceForRow(this);
});
displayTotal(total);
$("#myInput").keyup(function () {
total = 0;
var filtertext = $(this).val();
var regex = new RegExp(filtertext, 'i');
$rows.hide().filter(function () {
return regex.test($(this).text());
}).show();
$(".table tbody tr:visible").each(function () {
total += getPriceForRow(this);
});
displayTotal(total);
});
function getPriceForRow(row) {
$valor = $(row).find(".valor");
if ($valor.length) {
return parseFloat($valor.text().replace(/\./g, "").replace(",", "."));
}
return parseFloat(0);
}
function formatTotal(num) {
var parts = num.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ".");
return parts.join(",");
}
function displayTotal(total) {
$totalElement.html(formatTotal(total.toFixed(2)));
}
});
Ideally you can avoid your globals in this case. You may want to read into closures here on MDN . It is how you can simulate private scope to an extent in your script. More or less, wrapping up and protecting the values in the contexts they are needed (simplification, I know).
Global scope variables are often troublesome for a number of reasons. You can do some reading on this here
Here is a good library for formatting currency as well, accounting.js
I am a complete newbie in programming so be easy on me.
I want to print an array object into a table in HTML using getElementByID.
<script>
var ram = ["8GB", "3GB"];
var storage = ["500GB" , "120GB"];
document.getElementById("mac.r").innerHTML = ram[0];
document.getElementById("mac.s").innerHTML = storage[0];
</script>
And I want to print it in a table
<table width="600" border="6" cellpadding="5px">
<tr>
<td> Ram</td>
<td> Storage</td>
</tr>
<tr>
<td id="mac.r"></td>
<td id="mac.s"></td>
</tr>
</table>
I use a macbook and google chrome.
If you must keep your script inline place it at the bottom of your page. See below, you can view the fiddle here
Once the element exists that you need to populate, you then loop the the data you need and fill the related element with your data.
<html>
<body>
<table width="600" border="6" cellpadding="5px">
<tr>
<td> Ram</td>
<td> Storage</td>
</tr>
<tr>
<td id="mac.r"></td>
<td id="mac.s"></td>
</tr>
</table>
<script>
(function() {
var ram = ["8GB", "3GB"];
var storage = ["500GB", "120GB"];
var macR = document.getElementById('mac.r');
var macS = document.getElementById('mac.s');
for(var i = 0; i < ram.length; i++){
if (macR !== null) macR.innerHTML = macR.innerHTML + ram[i] + "<br>";
}
for(var i = 0; i < ram.length; i++){
if (macS !== null) macS.innerHTML = macS.innerHTML + storage[i] + "<br>";
}
})();
</script>
</body>
</html>
One simple approach is to use the array's build-in "forEach" method:
var ram = ["8GB", "3GB"],
storage = ["500GB" , "120GB"];
ram.forEach(function(element, index, array){
document.getElementById("mac.r").innerHTML += element;
});
storage.forEach(function(element, index, array){
document.getElementById("mac.s").innerHTML += element;
});
See it here: http://jsfiddle.net/S3CY4/
Be aware though its mostly supported in modern browsers and it may not be the most performant approach.
I have a id on my page that I am trying to retrieve a number from and add a value to. For instance:
<td id="qty_295518">1700</td>
var quantity = 1;
var currentQty = +(jQuery.trim($("#qty_295518").text()));
var newQty = parseInt(currentQty, 10) + quantity;
When I try and add the numbers together it come out looking like this:
17001 instead of 1701
It is just appending the 1 to the end of 1700 instead of adding it to 1700. I have tried to use parseInt, +() but to no avail. Anyone have any suggestions?
Thanks
I made a few changes from yours but they're not too different. Here's my jsfiddle, maybe it will help? I've put an alert in there to let you know that the correct value is being returned
http://jsfiddle.net/muBJd/1/
I don't know if this is the case in your actual code, but make sure that the td is wrapped in tr and table tags.
Html
<table>
<tr>
<td id="qty_295518">1700</td>
</tr>
</table>
Jquery / Javascript
var quantity = 1;
var targetQuantity = $('#qty_295518').text();
var myInteger = parseInt(targetQuantity, 10);
var addingQuantities = myInteger + quantity;
It seems that you are doing something wrong outside from jquery code, because jquery code is working fine as I wrapped the <td> inside the <tr> of <table>. something like this.
<table>
<tr>
<td id="qty_295518">1700</td>
</tr>
</table>
DEMO
Try this:
var quantity = 1;
var currentQty = +(jQuery.trim($("#qty_295518").text()));
var newQty = parseInt(currentQty, 10);
newQty += quantity;
i have a problem with my javascript and html
i was trying to write a html element using a function from my javascript
here's my code
function write();
{
for(var i=0;i<arr.length;i++)
{
document.write("<td>"+arr[i]+"</td><br>")
}
}
and code at my index.html, i want put that write inside my table row
<tr>
<script>write();</script>
</tr>
i have attached my javscript to my html document, but nothing happened
can u guys help me to put make that function work??
thanks guys!!
As per your question description, for writing html or dom elements say, you need to first create element(until you already have in which case you can use document.getElementById()) and then add text.
For creating:
# Create new dom element
var td = document.createElement("td");
Adding text:
td.appendChild(document.createTextNode('hiii'))
In your case:
function write(){
var element;
for(var i=0;i<arr.length;i++) {
element = document.createElement("td");
element.appendChild(document.createTextNode(arr[i]));
}
}
Give your row an id like this:
<tr id="myRow">
</tr>
Also i would recommend you to implement the function call in your javascript file.
Try something like this:
window.onload = function(){
write();
};
function write(){
for(var i = 0; i < arr.length; i++){
document.getElementById("myRow").innerHTML += "<td>" + arr[i] + "</td><br>";
}
}
you can check html below:
<table>
<tr id="myid" >
</tr>
</table>
and javascript would be like this
var row = document.getElementById("myid");
var x = row.insertCell(0);
x.innerHTML="New cell";
HTML:
<table>
<tr id='row'></tr>
</table>
JS:
function write(arr) {
var row = '';
for (var i = 0; i < arr.length; i++) {
row += '<td>'+arr[i]+'</td>'
}
document.getElementById('row').innerHTML = row;
}
write(['a', 'b', 'c', 'd']);
working demo: http://jsfiddle.net/uhaEL/
Using JavaScript in Greasemonkey, I'm attempting to pull individual cells and read the innerHTML of each cell to search for a given string.
There's a table of 3x3, and I want to search them in the order of the center first, then depending on situation, move to not-necessarily linear progression (i.e. top-left, top, left, top-right, bottom-left, right, bottom, bottom-right).
I've put each of the cells into an array, and using splice(), I assign the cell to a variable. For testing purposes, I throw up 2 alerts with the cell variable itself, then the cell innerHTML.
When I just use the variable, the alert says [object HTMLTableCellElement], but the innerHTML is undefined.
I've created a mock page to show my example. here's the code (Also at jsBin).
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<table>
<tr>
<td>0</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4<br>
center
</td>
<td>5</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
</table>
<script language="JavaScript">
var tables = document.getElementsByTagName("table");
tables[0].style.border = "thin solid red";
tables[0].id = "grid";
var grid = tables[0];
var cells = new Array();
cells[0] = grid.rows[0].cells[0]; // nw
cells[1] = grid.rows[0].cells[1]; // n
cells[2] = grid.rows[0].cells[2]; // ne
cells[3] = grid.rows[1].cells[0]; // w
cells[4] = grid.rows[1].cells[1]; // c
cells[5] = grid.rows[1].cells[2]; // e
cells[6] = grid.rows[2].cells[0]; // sw
cells[7] = grid.rows[2].cells[1]; // s
cells[8] = grid.rows[2].cells[2]; // se
var grid_string = "";
function HumanCount(cell) {
var human_regex = /Human/;
var humans = cell.innerHTML.split(human_regex);
var humans_length = humans.length - 1;
return humans_length;
}
for (a = 0; a < 9; a++) {
cells[a].count = HumanCount(cells[a]);
grid_string += cells[a].count + " ";
if (a == 2 || a == 5) {
grid_string += "<br>";
}
}
var direction = 0; // nw
var center = cells.splice(4, 1);
alert("center: " + center);
alert("innerHTML: " + center.innerHTML);
</script>
</body>
</html>
center is not an element, so it has no innerHTML property.
center is an array of elements, so if you use:
alert ("innerHTML: " + center[0].innerHTML);
you'll see what you expect.
~~~
That alert alert("center: "+center); is misleading, as it shows <td> the same as [<td>].
For more accurate (and less annoying) debugging don't use alert(). Use console.log, EG: console.log ("center: ", center); -- which would show the array as different from the element and doesn't throw up a modal dialog.