I have some HTML that looks as follows:
<table id="resultsTable" class="table table-bordered table-responsive table-hover table-condensed sortable">
<thead>
<tr>
<th>Company Name</th>
<th>Tours Offered</th>
<th>Average Rating</th>
<th>Total Reviews</th>
</tr>
</thead>
<tbody class="searchable">
#foreach (var item in Model.AccommodationList)
{
<tr>
<td class="accommodationName">
#Html.ActionLink(item.AccommodationName, "ViewHomePage", "AccommodationHomepage", new {accommodationId = item.AccommodationId}, null)
</td>
<td>
#Html.DisplayFor(modelItem => item.FormattedAddress)
</td>
<td>
<Deleted for brevity>
</td>
<td>
#Html.DisplayFor(modelItem => item.TotalReviews)
</td>
<td class="latitudeCell" style="display: none;">
#Html.DisplayFor(modelItem => item.Latitude)
</td>
<td class="longitudeCell" style="display: none;">
#Html.DisplayFor(modelItem => item.Longitude)
</td>
</tr>
}
</tbody>
</table>
I am trying to get the value of the accommodation name, latitude and longitude in each row with the following jQuery:
$('#resultsTable tbody tr').each(function () {
var latitude = $(this).find(".latitudeCell").html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
});
}
However I must be doing something incorrectly because I'm not able to get any values.
Use javascript table.rows function and textContent property to get the inner text of the cell like you can do something like below:
for(var i = 1, row; row = table.rows[i]; i++)
{
var col1 = row.cells[0].textContent;
var col2 = row.cells[1].textContent;
} var col3 = row.cells[2].textContent;
Don't use innerText it is much slower than textContent and also doesn't work in firefox.
I wrote up a fiddle and modified some of your code so I could put text in your cells, I am wondering if this will help you? If not could you write up a small fiddle and I can provide some more assistance.
https://jsfiddle.net/y3llowjack3t/8cL94hgq/
$('#resultsTable tbody tr').each(function () {
var latitude = $(this).find(".latitudeCell").html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
alert(latitude);
});
You are getting the data correctly but, you don't seem to do anything with the values you obtain from the table. And, after .each(), you will not have access to even the values from the last row since you're using local variables. You can create an array that has all the data.
Give this a try:
var locations = $('#resultsTable tbody tr').map(function() {
var location = {};
location.latitude = $(this).find(".latitudeCell").html();
location.longitude = $(this).find(".longitudeCell").html();
location.accommodationName = $(this).find(".accommodationName").html();
return location;
}).get();
console.log( locations );
//OUTPUT: [{"latitude": "<val>","longitude": "<val>", "accommodationName": "<val>"},{.....},....]
Your code works for me:
example
In the code you paste you put a } more, try to check if there's some issues with brakets.
Here is a working example. In your example, I did not see how you were calling your function. I enclosed your function in $().ready() so that it is called when the DOM is ready. You will want to call your function any time the tan;e content changes.
$().ready(function() {
$('div#cellValues').empty();
$('div#cellValues').append('<ul></ul>');
$('#resultsTable tbody tr').each(function(index) {
var latitude = $(this).find('.latitudeCell').html();
var longitude = $(this).find(".longitudeCell").html();
var accommodationName = $(this).find(".accommodationName").html();
$('div#cellValues ul').append('<li>' + accommodationName + ': [' + latitude + ',' + longitude + ']</li>');
});
});
#cellValues {
border: 1px solid red;
}
#cellValues::before {
content: "Cell Values:";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cellValues"></div>
<table id="resultsTable" class="table table-bordered table-responsive table-hover table-condensed sortable">
<thead>
<tr>
<th>Company Name</th>
<th>Tours Offered</th>
<th>Average Rating</th>
<th>Total Reviews</th>
</tr>
</thead>
<tbody class="searchable">
<tr>
<td class="accommodationName">accomidationName1</td>
<td>FormattedAddress1</td>
<td></td>
<td>TotalReviews1</td>
<td class="latitudeCell" style="display: none;">Latitude1</td>
<td class="longitudeCell" style="display: none;">Longitude1</td>
</tr>
<tr>
<td class="accommodationName">accomidationName2</td>
<td>FormattedAddress2</td>
<td></td>
<td>TotalReviews2</td>
<td class="latitudeCell" style="display: none;">Latitude2</td>
<td class="longitudeCell" style="display: none;">Longitude2</td>
</tr>
<tr>
<td class="accommodationName">accomidationName3</td>
<td>FormattedAddress3</td>
<td></td>
<td>TotalReviews3</td>
<td class="latitudeCell" style="display: none;">Latitude3</td>
<td class="longitudeCell" style="display: none;">Longitude3</td>
</tr>
</tbody>
</table>
Related
I have a html table with multiple rows and columns. I want to pull all the values by column id and compare with some matching string. If matches i want to enable a button on the page.
Could you please let me know how to refer the column by id in $(document).ready function.
Here is the table
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<th:block th:each="it : ${data}">
<tr>
<td th:text="${it.id}">id</td>
<td th:text="${it.name}">name</td>
<td th:text="${it.place}">place</td>
</tr>
</th:block>
</table>
Button:
style="visibility:hidden">Submit
$(document).ready(function(){
//here i want to pull the place column and verify if one of the
places matches my input string enable submit button
$("#submitbutton").css("visibility", "visible");
}
}
This function will take all information inside you td and search for the string you looking for :
But i cannot get the point that you search for a particular string instead of searching for an object.
const addresses = [...document.querySelectorAll(".address")];
const serchFromList = (arr, str) => {
return arr.map(el =>
el = el.innerHTML
).filter(el => el === str)
}
console.log(serchFromList(addresses, "NY"))
/* in case you want a boolean you can use some*/
const isAddressExist = (arr, str) => {
return arr.map(el =>
el = el.innerHTML
).some(el => el === str)
}
console.log(isAddressExist(addresses, "NY"))
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<th>
<tr>
<td>4545</td>
<td>5454</td>
<td>65687</td>
</tr>
<tr>
<td>aziz</td>
<td>david</td>
<td>paul</td>
</tr>
<tr>
<td class='address'>NY</td>
<td class='address'>MTL</td>
<td class='address'>BC</td>
</tr>
</th>
</table>
Should be pretty doable with XPath if you don't want to add extra attributes to Place cell. Just find out the position of Place column and get the text from the same position of <td>.
// Get the table node first
let node = document.getElementById('data')
// Find out position of `Place` column
let nth = document.evaluate('count(//th[text()="Place"]/preceding-sibling::*)+1', node).numberValue
// Get all the place cell by the position
let placeCells = document.evaluate(`//td[position()=${nth}]`, node)
// Get all the place names
let places = [],
placeNode = placeCells.iterateNext()
while (placeNode) {
places.push(placeNode.textContent)
placeNode = placeCells.iterateNext()
}
console.log(places)
// ['NYC', 'SF', 'LA']
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<tbody>
<tr>
<td>0001</td>
<td>Mary</td>
<td>NYC</td>
</tr>
<tr>
<td>0002</td>
<td>John</td>
<td>SF</td>
</tr>
<tr>
<td>0003</td>
<td>Bob</td>
<td>LA</td>
</tr>
</tbody>
</table>
I would like to know how could I assign a table row an id which is systematically as a counter. It can be a string + a counter as follow:
<table>
<tr id="Row1"> # it can be only a number => id="1"
<tr id="Row2"> # it can be only a number => id="2"
<tr id="Row3"> # it can be only a number => id="3"
.....
<tr id="Row5000"> # it can be only a number => id="5000"
</table
Because I have thousands of rows and then could not assign id to them manually. This is why I want to assign them via XSLT. Does anybody know how could I do so? Thanks.
// javascript
var table = document.querySelectorAll('table tr');
{
for(var i=0;i<table.length;i++){
table[i].setAttribute("id",i+1);
}
//jquery
$("table tr").each(function(index,object) {
object.attr("id",(index+1));
})
$("table tr").each(function(i, tr) {tr.id = 'Row' + (i+1);})
explanation: you can find each tr in table and assign id for each one.
First you assign an id attribute to your table like this
<table id="mytable">
<tr></tr>
<tr></tr>
....
</table>
Then add a script at the bottom of your document
<script>
(function() {
var rows = document.getElementById("mytable").rows;
for(var i = 1; i <= rows.length; i++) {
rows[i-1].id = 'Row'+i;
}
})();
Its a pure javascript solution. No jQuery required.
Assign your table an id. here its newTable then iterate and set the attibute
<script>
function getit(){
$('#newTable').find('tr').each(function(index){
var x= this.setAttribute("id","Row"+[index]);
console.log(x);
})
}
</script>
hope that helped.
You Can Use This:
Your CSS
<style>
body {
counter-reset: section;
}
table tbody tr th::before {
counter-increment: section;
content: "Section " counter(section);
}
table tbody tr th::before {
content: counter(section);
}
</style>
Your Html
<table class="table">
<thead>
<tr>
<th colspan="6">
</th>
</tr>
<tr>
<th scope="col">#</th>
<th scope="col">f1</th>
<th scope="col">f2</th>
<th scope="col">f3</th>
<th scope="col">f4</th>
<th scope="col">f5</th>
</tr>
</thead>
<tbody>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
</tbody>
</table>
I want to search a table by the values in a single column.
The table looks like this:
<table class="table main-content">
<thead>
<td><b>Title</b></td>
<td><b>Name</b></td>
<td><b>State (D)</b></td>
<td><b>Party</b></td>
<td><b>Room</b></td>
<td><b>Phone #</b></td>
<td><b>Special Role(s)</b></td>
</thead>
<tbody id="congress">
<tr>
<td>Senator</td>
<td>Alexander, Lamar</td>
<td>TN</td>
<td class="republican">Rep.</td>
<td>455 Dirksen</td>
<td>(202) 224-4944</td>
<td></td>
</tr>
<tr>
<td>Senator</td>
<td>Barrasso, John</td>
<td>WY</td>
<td class="republican">Rep.</td>
<td>307 Dirksen</td>
<td>(202) 224-6441</td>
<td></td>
</tr>
...
I want to be able to search the table by a given column, say names (index 1) or state (index 2). I've tried jets.js but it only allows one instance per page while I require at least two. JQuery is preferred, JS is fine, and external libs are ok but not optimal.
Cheers!
Edit:
I've tried using the following:
var $rows = $('#congress tr');
$('#stateSearch').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
The above code searches all of the columns in the table. How can I adjust it to search only for a specific column? (By index.)
The goal is to hide all of the tr that don't match the query in the given column
Something like this
function isFound(name, state)
{
$("table tbody").find("tr").each (function(){
var trElem = $(this);
if (($(this).find("td:eq(1) a").text() == name) && ($(this).find("td:eq(2)").text() == state))
return trElem;
})
return false;
}
Usage:
if (tr = isFound ('Firstname Lastname', 'State'))
tr.remove();
or, if you have more than one elements, use a loop for removing
while (tr = isFound ('Firstname Lastname', 'State'))
tr.remove();
Here's an example that will hide all rows where the State column (index 3) is TN. You can adapt it as you need:
$('td:nth-child(3)').each (function(){
if( $(this).val() == 'TN' )
$(this).parent().hide();
});
Another easy solution would be to use Datatables, which have a built-in search feature and methods to search by column. It may be overkill for your project, but take a look anyway for the future.
DataTables Example
You could reinvent the wheel, but it's probably better to just use DataTables unless you have an expressed need to do otherwise:
var $table = $('table');
// Setup - add a text input to each footer cell
$table.find('tfoot th').filter(':eq(1),:eq(2)').css('visibility', 'visible').each(function() {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
// DataTable
var table = $table.DataTable({
lengthChange: false
});
// Apply the search
table.columns().every(function() {
var col = this;
$('input', this.footer()).on('keyup change', function() {
if (col.search() !== this.value)
col.search(this.value).draw();
});
});
table tfoot tr th {
visibility: hidden;
}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/r-2.1.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/bs-3.3.7/jq-2.2.4/dt-1.10.13/r-2.1.1/datatables.min.js"></script>
<table class="table table-striped main-content">
<thead>
<tr>
<th>Title</th>
<th>Name</th>
<th>State (D)</th>
<th>Party</th>
<th>Room</th>
<th>Phone #</th>
<th>Special Role(s)</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Title</th>
<th>Name</th>
<th>State (D)</th>
<th>Party</th>
<th>Room</th>
<th>Phone #</th>
<th>Special Role(s)</th>
</tr>
</tfoot>
<tbody id="congress">
<tr>
<td>Senator</td>
<td>Alexander, Lamar</td>
<td>TN</td>
<td class="republican">Rep.</td>
<td>455 Dirksen</td>
<td>(202) 224-4944</td>
<td></td>
</tr>
<tr>
<td>Senator</td>
<td>Barrasso, John</td>
<td>WY</td>
<td class="republican">Rep.</td>
<td>307 Dirksen</td>
<td>(202) 224-6441</td>
<td></td>
</tr>
</tbody>
</table>
try this:
var text = $(this).find('td:eq(1),td:eq(2)').text().replace(/\s+/g, ' ').toLowerCase();
I have the following table:
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
I need a way to add/sum all values grouped by category, ie: add/sum all values in cat1, then add/sum all values in cat2. For each group I will do something with the total.
So I was hoping for something like:
for each unique category:
sum values in category
do something with this category total
For cat1 the total would be 123 + 486. Cat2 would just be 356. And so on if there were more categories.
I would prefer a purely javascript solution, but JQuery will do if that's not possible.
If I understand you correctly, you do a repeat of each td:first-child (The category cell).
Create a total object. You can check if the category is exist in it for each cell. If so, add current value to the stored value. If not, insert new property to it.
Like this:
var total = {};
[].forEach.call(document.querySelectorAll('td:first-child'), function(td) {
var cat = td.getAttribute('class'),
val = parseInt(td.nextElementSibling.innerHTML);
if (total[cat]) {
total[cat] += val;
}
else {
total[cat] = val;
}
});
console.log(total);
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
Here's a simple approach using only javascript
//grab data
var allTR = document.getElementsByTagName('TR');
var result = {};
//cycle table rows
for(var i=0;i<allTR.length;i+2){
//read class and value object data
var class = allTR[i].getAttribute('class');
var value = allTR[i+1].innerText;
//check if exists and add, or just add
if(result[class])
result[class] += parseInt(value);
else
result[class] = parseInt(value);
}
You have to use getElementsByTagName("td"); to get all the <td> collection and then you need to loop through them to fetch their innerText property which later can be summed up to get the summation.
Here is the working Fiddle : https://jsfiddle.net/ftordw4L/1/
HTML
<table id="tbl1">
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
<tr>
<td class="total"><b>Total</b></td>
<td class="totalValue"></td>
</tr>
</table>
Javascript
var tds=document.getElementsByTagName("td");
var total=0;
for (var i = 0; i<tds.length; i++) {
if (tds[i].className == "value") {
if(total==0) {
total = parseInt(tds[i].innerText);
} else {
total = total + parseInt(tds[i].innerText);
}
}
}
document.getElementsByClassName('totalValue')[0].innerHTML = total;
Hope this helps!.
here is a solution with jQuery :) if you are interested. it's pretty straightforward
var sumCat1 = 0;
var sumCat2 = 0;
$(".cat1 + .value").each(function(){
sumCat1 += parseInt($(this).text());
})
$(".cat2 + .value").each(function(){
sumCat2 += parseInt($(this).text());
})
console.log(sumCat1)
console.log(sumCat2)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>
A simple approach in JQuery...
var obj = {};
$('tr').each(function() {
$this = $(this)
if ($this.length) {
var cat = $(this).find("td").first().html();
var val = $(this).find("td").last().html();
if (cat) {
if (!obj[cat]) {
obj[cat] = parseInt(val);
} else {
obj[cat] += parseInt(val);
}
}
}
})
console.log(obj)
Trying to store all the information that getting from JSONP in the table.
Have done the test with 'alert' to make sure that there are more info that only one line and can see that there are more info that one.
But when run it, in the table I can see title row and first row.
Can somebody correct my error?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.example.com/v1/deal/hotel?apikey=xxx&format=JSONP",
dataType : "jsonp",
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, value ) {
alert( index + ": " + value.StarRating + " , "+ value.Url);
});
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var from = parsed_json['Result'][0]['StartDate'];
document.getElementById("from").innerHTML = from;
var to = parsed_json['Result'][0]['EndDate'];
document.getElementById("to").innerHTML = to;
var nights = parsed_json['Result'][0]['NightDuration'];
document.getElementById("nights").innerHTML = nights;
var currency = parsed_json['Result'][0]['CurrencyCode'];
document.getElementById("currency").innerHTML = currency;
var price = parsed_json['Result'][0]['Price'];
document.getElementById("price").innerHTML = price;
var link = parsed_json['Result'][0]['Url'];
document.getElementById("link").innerHTML = link;
//how to represent enlaces
var city = parsed_json['Result'][0]['City'];
document.getElementById("city").innerHTML = city;
var country = parsed_json['Result'][0]['CountryCode'];
document.getElementById("country").innerHTML = country;
var stars = parsed_json['Result'][0]['StarRating'];
document.getElementById("stars").innerHTML = stars;
}
});
});
</script>
</head>
<body>
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr>
<td id="from"></td>
<td id="to"></td>
<td id="nights"></td>
<td id="currency"></td>
<td id="price"></td>
<td id="link"></td>
<td id="city"></td>
<td id="country"></td>
<td id="stars"></td>
</tr>
</table>
</body>
</html>
The result of the Ajax callback is:
callback({"Errors":[],"Result":[{"FoundDate":"2013-12-04T16:11:36-08:00","CurrencyCode":"USD","NightDuration":"2.0","EndDate":"12/08/2013","Headline":"Cairo 5 Star Hotel, $36/night","IsWeekendStay":"true","Price":"36.0","StartDate":"12/06/2013","Url":"http‍://www.example.com/hotel/...&startDate=12/06/2013&endDate=12/08/2013&bid=0&sid=0","City":"Cairo","CountryCode":"EG","NeighborhoodLatitude":"30.0152","NeighborhoodLongitude":"31.1756","Neighborhood":"Cairo West - Giza","StarRating":"5.0","StateCode":"EG"},{"FoundDate":"2013-12-04T14:51:44-08:00",
If you have more than one line in result, then you have to -
Loop through it in the callback. You are not looping through it now. You are looping only for alert.
Dynamically create a new row in table for each line. You can clone the exiting tr for this using jquery clone method. But replace the id with 'class`.
Add data to that row pertaining to the line by modifying innerHtml of each td in the newly created row.
Finally, Append the row to the table
HTML -
<table id="t">
<tr>
<th>Start date</th>
<th>End date</th>
<th>Nights</th>
<th>Currency</th>
<th>Price</th>
<th>Link</th>
<th>City</th>
<th>Country Code</th>
<th>Star Rating</th>
</tr>
<tr class="first">
<td class="from"></td>
<td class="to"></td>
<td class="nights"></td>
<td class="currency"></td>
<td class="price"></td>
<td class="link"></td>
<td class="city"></td>
<td class="country"></td>
<td class="stars"></td>
</tr>
</table>
Javascript -
success : function(parsed_json) {
$.each(parsed_json.Result, function( index, record ) {
$row = $('.first').clone();
var from = record['StartDate'];
$row.find('.from').html(from);
//Similarly repeat the above two lines for other columns
//...
$('#t').append($row);
});
}