How to add html contents taken from an html table? - javascript

I have this script
$('table#preview td.price').each(function(){
var price = parseInt($(this).html());
var total;
if(price == ''){
price = 0;
}
total += price;
alert(total);
});
What it does is get the column that has the class price then supposedly adds it all up.
However, all I get from this code is NaN. I don't get what's wrong with the code.
Please note the script if(price == ''). I've done this because initially there are no contents in the table.
Edit: Here the html
<table>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
<tr>
<td>pen</td>
<td class="price>6</td>
<td>paper</td>
<td class="price>8</td>
</tr>
</table>

Try using the .text() method instead of .html() method, it should hopefully help get rid of the NaN errors. You'll want to declare the total outside the scope of each iteration so it doesn't get reset each time. Try giving this a go, I've simplified it slightly to also include a check against the number price:
var total = 0;
$('table#preview td.price').each(function()
{
var price = parseInt($(this).text());
if (!isNaN(price))
{
total += price;
}
});
alert('The total is: ' + total);
Update
Here's a jsFiddle. N.B. .html() should also work.

Related

Concatenating numbers instead off adding them together

Having read for hours on the web and tried various things I am lost as to the answer to my problem. I want to be able to check a checkbox and get the value from an input box. ie If more than 1 checkbox is checked the values (both £100) would produce a sum of £200. I am getting "100100"!
My html table is produced with PHP with value '$price' from a mySQL database as a DECIMAL (10,2):
<html>
<table>
<tr>
<td><input name='payInvoice' type='checkbox' onchange='add()'></td>
<td><input id='amountToPay' value=$price></td>
</tr>
</table>
</html>
and javascript:
<script>
function add(){
var payOff = " "
document.getElementById('poff').value = "";
var payoff = document.getElementsByName("payInvoice");
for (var i=0; i<payoff.length; i++){
if (payoff[i].checked == true){
amount = document.getElementById("amountToPay");
$s = parseInt(amount.value);
payOff += ($s) ;
document.getElementById('poff').value = payOff;
}
}
}
</script>
Change var payOff = " " to var payOff = 0 and it will work.You are adding string to integers hence its not working.
So when you write payOff += $(s); you are actually doing payOff = (" " + interger) which is basically string concatenation hence you will always get a string back

JQuery td:contains

So at work, I have to go through a list that contains thousands of users and select a checkbox by the ones I need to delete. Long story short it's a slow process. To make things faster I made this script to run in chrome using developer tools in the console.
var usernames = ["jimmy123"];
for(var i=0;i<usernames.length;i++)
{
jQuery("td:containsExact("+usernames[i]")").find('[type=checkbox]').parent().attr('checked', true).css("background-color", "red");
}
var count = jQuery("[type='checkbox']:checked").length;
alert("Everything Returned Okay!");
alert(usernames.length);
alert(count + " Checkboxes Checked!");
The Trouble is that let's say a user created 3 because they forgot the login for them "not uncommon" and their username is:
jimmy123
jimmy1234
jimmy12345
If I need to just check the box next to jimmy123 for removal my script selects all 3 since they have mostly the same username.I tried some filters but the result was the same.
Backend Screenshot
You can use filter() function here to match the exact text in the td and then mark the checkbox selected. See the below script, you didn't provide the HTML so I added a sample table with some td containing usernames and checkbox, you should update the script accordingly
$(function($) {
var usernames = ["jimmy123", "omer"];
for (var i = 0; i < usernames.length; i++) {
$("tr>td").filter(function() {
return $(this).text() == usernames[i]
}).find('[type=checkbox]').attr('checked', true).css("background-color", "red");
}
var count = jQuery("[type='checkbox']:checked").length;
console.log("Everything Returned Okay!");
console.log("usernames.length" + usernames.length, usernames);
console.log(count + " Checkboxes Checked!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="checkbox">omer</td>
<td><input type="checkbox">omer123</td>
<td><input type="checkbox">omer6565</td>
<td><input type="checkbox">omer63645</td>
<td><input type="checkbox">omer021</td>
<td><input type="checkbox">omer521</td>
<td><input type="checkbox">jimmy123</td>
</tr>
</table>
EDIT
You can assign an id to your table say my-table and then change the selector in the code above from
$("tr>td").filter(function() {
to the following
$("#my-table tr>td").filter(function() {
The exact selector could be suggested when you add the HTML for your user listings that you are using the script with.
EDIT2
According to your html it should be
$(function($) {
var usernames = ["jimmy123", "omer"];
for (var i = 0; i < usernames.length; i++) {
$("#listContainer_datatable tr td").filter(function() {
return $(this).text() == usernames[i]
}).find('[type=checkbox]').attr('checked', true).css("background-color", "red");
}
var count = jQuery("[type='checkbox']:checked").length;
console.log("Everything Returned Okay!");
console.log("usernames.length" + usernames.length, usernames);
console.log(count + " Checkboxes Checked!");
});

Create an element using javascript

I have a html table
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
data here <3 ....
</tbody>
</table>
and here is my php (sample.php)
<?php
Query Code here..
Query Code there..
and so on
//this is the way I populate a table
while (query rows) {
echo '<tr>';
echo '<td>Sample Data</td>';
echo '</tr>;
}
?>
So to make this work and to populate the table this is what I do.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
<?php
include 'folder_location/sample.php';
?>
</tbody>
</table>
Disregard the image of the ouput but when I go to Inspect Element or even Ctrl + u I will see my table structure now is like this.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
<tr>
<td>Sample Data</td>
</tr>
</tbody>
</table>
Now here is the thing. I do not do that this is what I do.
$("#rpttable tr").remove();
for (i = 0; i < data.length; i++) {
tr = $("<tr />");
for (x in data[i]) {
td = $("<td />");
td.html(data[i][x]);
tr.append(td);
}
rpttable.append(tr);
}
Same output It does populate the table but when I go to Inspect Element or even Ctrl + u the output is.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
**This is the part missing**
</tbody>
</table>
My question here is how can I literaly create an element usung javascript/ajax? same output in php. I mean write the element.
** Updated **
I am trying to run a css class from an external file and If I manualy edit it to suits my needs I will a long hour and also Its hard for me to explain its a class for table. I tried to use that class using default value in <table>. You know manualy write it at the back end. now Im trying to populate it using a php and ajax so, so far so good it does populate but when I try to run the class the class does not work.
TYSM
Using jquery you can add html rows to the tbody using:
$("#rptbody").html("<tr><td>value</td></tr>");
Is this what you want to do?
You can use JQuery append() method:
$('#rptbody').append('<tr><td>my data</td><td>more data</td></tr>');
In case you need to insert after last row:
$('#rptbody> tbody:last-child').append('<tr>...</tr><tr>...</tr>');
for (i = 0; i < 5; i++) {
let tr = $("<tr />");
for (j=0; j < 5;j++)
tr.append($("<td />",{html:j,class:"tbl"}));
$("tbody").append(tr);
}
.tbl{border:1px solid pink;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody></tbody>
</table>
You have asked roughly two questions. Let's break it down.
My question here is how can I literaly create an element usung javascript/ajax?
You are already doing this with your Javascript (client-side) code. It looks like you're using jQuery syntax, so we'll stick with that. This does create an element and inserts it into the page.
var $el = $("<div>I'm a new div element</div>");
$('body').append( $el );
This creates a new element, assigns it to the $el variable, and then appends it to the body of the page. This will not show up in "View Page Source" view, however. Why? Because this modifies the DOM -- the Dynamic Object Model.
To see this new element, you'll either need to look at the rendered output (what the user/you sees), or open up your browser's DevTools (often <F12>, or right-click -> inspect). In the DevTools, find the "Inspector" tab (or equivalent), then look for your new element in this live view of the DOM.
... same output in php.
In short, you can't. What Ctrl+U / View Page Source shows is the page as it was initially received from the server. This would be the exact content you would see if you were to use a command line tool, like curl or wget:
curl http://url.to.your.com/page
Since you include 'folder_location/sample.php' at the server, this is included in the page before the browser sees it. For your edification, I would consider reading up on the DOM.
Wikipedia
W3
Try this:
$("#rpttable tbody tr").remove();
var content = '' ;
for (i = 0; i < data.length; i++) {
content += "<tr>" ;
for (x in data[i]) {
content += "<td>" + data[i][x] + "</td>" ;
}
content += "</tr>" ;
}
$("#rpttable tbody").html(content) ;
Updated
I am using Google Chrome too. Please try the below code, and check the inspect element each time you add a new row. You can see the html in the Inspect Element changing!
function AppendNewRowToTable() {
var trLen = $("table tbody tr").length ;
var content = "" ;
content += "<tr>" ;
for (i = 0; i < 5; i++) {
content += "<td>" + trLen + "-" + i + "</td>" ;
}
content += "</tr>" ;
$("table tbody").append(content) ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Add new Row
<br />
<table>
<thead>
<tr>
<th>Title 01</th>
<th>Title 02</th>
<th>Title 03</th>
<th>Title 04</th>
<th>Title 05</th>
</tr>
</thead>
<tbody></tbody>
</table>
It seems your intent is to append extra rows to the table in your html response generated from your PHP script.
For that you don't need to clear all existing rows.
$("#rpttable tr").remove();
Build an array of rows and append once to your table body.
var $tbody = $('#rptbody');
var tableRowAdditions = [];
for (var i = 0; i < data.length; i++) {
var $tr = $("<tr></tr>");
for (var x in data[i]) {
var $td = $("<td></td>");
$td.html(data[i][x]);
$tr.append(td);
}
tableRowAdditions.push(tr);
}
$tbody.append(tableRowAdditions);
For a "pure" JavaScript approach, you can create elements using the createElement Web API
For example:
A paragraph with text "Hello" would be
var container = document.getElementById('rptbody');
var hello = document.createTextNode('Hello');
var helloParagraph = Document.createElement('p');
// Add text to paragraph
helloParagraph.appendChild(hello);
// Append to container
container.appendChild(helloParagraph);
The best way to create elements using jQuery is to use the following format:
// Create the TR and TD elements as jQuery objects.
var tr = $("<tr></tr>", {
"id":"tr1",
"class":"tr"
});
var td = $("<td></td>", {
"id":"td1",
"class":"td",
"text": "Sample Data",
click: function() {
// optional: Function to attach a click event on the object
alert("Clicked!");
}
});
// Attach the element to the document by appending it
// inside rptbody (after all existing content inside #rptbody)
$("#rptbody").append(tr);
tr.append(td);
// OR, Attach the element to the document by prepending it
// inside rptbody (before all existing content in #rptbody)
$("#rptbody").prepend(tr);
tr.append(td);
// OR, Attach the element to the document by completely replacing the content of #rptbody
$("#rptbody").html(tr);
tr.append(td);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
</tbody>
</table>

Fetching the innerHTML from TD in jQuery

Hi I am using Sharepoint 2010 page, where I have the HTML snipet with the following structure:
<tr>
<td></td>
<td class="ms-vb2"></td>
<td class="ms-vb2"></td>
<td class="ms-vb2"></td>
<td class="ms-vb2"></td>
<td class="ms-vb2"><nobr><b>Sum= 72</b></nobr></td>
<td class="ms-vb2"><nobr><b>Sum= 66</b></nobr></td>
</tr>
Now I want to get the value 72 and 66 from the TD tag in a var, so that I can use these values in the client scripts.
The "Sum=" part of the TD is not supposed to change. And the ID of the table is randomly generated by sharepoint so I can't do anything with that as well.
Please help.
Thanks,
$(".ms-vb2 b").each(function(td) {
var s = td.hmtl().replace("Sum= ", "");
$("body").append(s);
});
Here's the working fiddle.
Try like below, It will help you..
Fiddle : http://jsfiddle.net/RYh7U/150/
$('td.ms-vb2').each(function() {
var value = $(this).text();
if(value !="")
alert(value);
//If you want to replace the Sum= in Text then try the below code
$(this).text($(this).text().replace("Sum= ",""));
});
Here is the solution- took time for me to generate the same.. :)
var arrValue = "";
$('td.ms-vb2').filter(function (i) {
if ($(this).html().indexOf('Sum=') > 0) {
mystring = $(this).html();
var result = /\d+(?:\.\d+)?/.exec(mystring);
//console.log(arrValue)
arrValue = result[0] + "," + arrValue
}
});
Thanks

Jquery group by td with same class

I have the current table data:
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr>
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
What I want to do is groupby the TDs which are the same, and sum the values on the second td to get the total. With that in mind I´ve put the name of the product to be a class on the TR (don't know if it is needed)
and I've coded the current javascript:
$(".groupWrapper").each(function() {
var total = 0;
$(this).find(".td2").each(function() {
total += parseInt($(this).text());
});
$(this).append($("<td></td>").text('Total: ' + total));
});
by the way the current java scripr doesn't groupby.
Now i'm lost, I don't know what else I can do, or if there is a pluging that does what I want.
</tr class="Violão"> This doesn't make sense. You only close the tag: </tr>. And I'm assuming you know that since the rest of your code is proper (except for your classnames. Check this question out).
If you want to add the values of each <td> with a class of td2, see below.
Try this jQuery:
var sum = 0;
$(".td2").each(function(){
sum = sum + $(this).text();
});
This should add each number within the tds to the variable sum.
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr class="Violão">
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
var dictionary = {};
$("td").each(function(){
if(!dictionary[$(this).attr("class"))
dictionary[$(this).attr("class")] = 0;
dictionary[$(this).attr("class")] += parseInt($(this).html());
});
// declare an array to hold unique class names
var dictionary = [];
// Cycle through the table rows
$("table tr").each(function() {
var thisName = $(this).attr("class");
// Add them to the array if they aren't in it.
if ($.inArray(thisName, dictionary) == -1) {
dictionary.push(thisName);
}
});
// Cycle through the array
for(var obj in dictionary) {
var className = dictionary[obj];
var total = 0;
// Cycle through all tr's with the current class, get the amount from each, add them to the total
$("table tr." + className).each(function() {
total += parseInt($(this).children(".td2").text());
});
// Append a td with the total.
$("table tr." + className).append("<td>Total: " + total + "</td>");
}
Fiddler (on the roof): http://jsfiddle.net/ABRsj/
assuming the tr only has one class given!
var sums = [];
$('.td2').each(function(){
var val = $(this).text();
var parentClass = $(this).parent().attr('class');
if(sums[parentClass] != undefined) sums[parentClass] +=parseFloat(val);
else sums[parentClass] = parseFloat(val);
});
for(var key in sums){
$('<tr><td>Total ('+key+')</td><td>'+sums[key]+'</td></tr>').appendTo($('table'));
}
I would give the table some ID and change to appendTo($('#<thID>'))
The solution:
http://jsfiddle.net/sLysV/2/
First stick and ID on the table and select that first with jQuery as matching an ID is always the most efficient.
Then all you need to do is match the class, parse the string to a number and add them up. I've created a simple example for you below
http://jsfiddle.net/Phunky/Vng7F/
But what you didn't make clear is how your expecting to get the value of the td class, if this is dynamic and can change you could make it much more versatile but hopefully this will give you a bit of understanding about where to go from here.

Categories

Resources