I am running a PHP + JQuery + DataTables page. Everything went fine and I have a similar mark up from the following:
.......
<tbody>
<tr data='1'>
....
</tr>
<tr data='2'>
....
</tr>
<tr data='1'>
....
</tr>
<tr data='8'>
....
</tr>
<tr data='2'>
....
</tr>
<tr data='7'>
....
</tr>
<tr data='7'>
....
</tr>
.
.
.
</tbody>
I need to get all the data attribute of all the tr in an array, well in the case of the above table, its:
var data_values = [1, 2, 8, 7];
I think that the logic may somewhat starts with $('tr').attr('data') but it returns undefined. I've performed already a query to the database and it also returns an array:
var database_returned_values = [2, 8];
My goal from the start is to remove the tr elements that are not found in the database_returned_values array. My solution is to subtract database_returned_values array from data_values. The difference will be the trs to remove. But I cannot even start to fetch data_values. How can I retrieve the data attributes of all tr and put it in an array or are there any easier way to do this?
In this case, the trs to remove are those which have data attribute of [1, 7];
You can use each() to iterate all the tr:
var data = new Array();
$("table tbody tr").each(function(){
if($.inArray($(this).attr("data")) == -1) // check if not in array
data.push($(this).attr("data"))
})
The data property needs to have something after it.
<tr data-id='7'>
And then jQuery has a nice method you can use called data.
$("tr").data("id")
You can get all the trs, then iterate them. Then, you have to read the data-* attribute (you should'n use only data="anything") and add to an empty array. Then, remove duplicates.
As long as you are using jQuery, you can do this with:
<table>
<tr data-id="1"></tr>
<tr data-id="3"></tr>
<tr data-id="1"></tr>
<tr data-id="4"></tr>
<tr data-id="4"></tr>
<tr data-id="7"></tr>
</table>
var ids = [];
$("table tr").each(function(index, item) {
ids.push($(item).data("id"));
})
alert($.unique(ids));
Fiddle: http://jsfiddle.net/chrisbenseler/s8pytwdz/
Then, iterate this new array ($.unique(ids)) and check whatever you need to check.
Related
I'm using Datatables and mark ids of my table with
<tr data-id='1'>
tags. I want to get the ids of selected rows. I tried this but it doesn't seem to work:
var $issueID = $(my_table.rows('.selected').nodes()).data('id');
$.each($issueID, function (value, index ) {
alert(value);
});
If I want to do it for a single row it works fine if I use
row().node()
but I can't get it right for many rows.
This should do the trick:
var selectedIds = [];
var my_table = $('#my_table').DataTable();
my_table.rows('.selected').every( function() {
selectedIds.push(this.data().id);
});
As Mike mentioned in a comment, notice that a capital D which is used to initialise the DataTable here. $().DataTable() returns a DataTables API instance, while $().dataTable() will also initialise a DataTable, but returns a jQuery object.
While searching for the same answer I came across this article. I modified the code in your question to find a working solution.
var inactiveRecord = $(my_table.rows('.selected').nodes());
$.each(inactiveRecord, function (idx, value) {
alert($(value).data('id'));
});
You should use a Class to do this in addition to your data-id.
JQUERY
$('.row').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
HTML
<tr class="row" data-id="1">
<td></td>
</tr>
<tr class="row" data-id="2">
<td></td>
</tr>
<tr class="row" data-id="3">
<td></td>
</tr>
or without a Class you could just use
$('tr').each( function() {
var value = $(this).attr('data-id');
alert(value);
})
I recommend adding a class to tr so you don't accidentally get it mixed up with other rows that may not need to be counted.
I have a list of HTML tables given by pandas data frame in the format of:
list_html =
[<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>score</th>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0.776959</td>
<td>grade</td>
<td>grade</td>
</tr>
<tr>
<th>1</th>
<td>0.414527</td>
<td>class</td>
<td>class</td>
</tr>, ... , ... ]
I am trying to visualize this data in an html page and could not do it. I do not have enough experience in web development. My goal is to use JavaScript to loop through each item the list and visualize them below each other in html. It would be great if anybody can help!
This is what I tried so far, its probably completely wrong:
var list_html = list_html // list of html codes as a javascript variable.
var arrayLength = analysis.length;
for (var i in list_html) {
document.getElementById("analysis_1").innerHTML = list_html[i];
}
Given a valid array of strings list_html (actually list_html is not a valid array of strings, since the markup in each entry is not wrapped in quotes) and a container in the DOM with id "analysis_1" it's simply a matter of:
var container = document.getElementById('analysis_1');
for (var i = 0; i < list_html.length; i++) {
container.innerHTML += list_html[i];
}
UPDATE:
well... in your scenario there is no need at all for a loop, you can simply inject a single string by joining the elements in the array:
document.getElementById('analysis_1').innerHTML = list_html.join('');
fast and simple! :)
using jquery's selectors :
Give the 'td' which contains the data a class name, eg: 'MyTd';
Select them all: $(.MyTd).text()
Done!
I want the data-id of all next tr of selected tr in an array. I use this code but this is not a good one.
var ids = Array.prototype.slice.call($("tr.selected").nextAll('tr'));
alert(ids)
.map(function (tr) {
return tr.getAttribute('data-id')
});
Use jQuery map() and get() methods
// iterate over elements using map and generate array elelements
var res = $("tr.selected").nextAll('tr').map(function(){
// get data attribute value
return $(this).data('id');
// get the result object as an array using get method
}).get();
If you want to get all siblings attribute value then use siblings() method instead.
var res = $("tr.selected")
// get all sibling tr
.siblings()
// iterate over elements using map and generate array elelements
.map(function(){
// get data attribute value
return $(this).data('id');
// get the result object as an array using get method
}).get();
In fact the code may look like that:
var ids = $('tr.selected').nextUntil('.selected').map(function() {
return $(this).data('id');
}).get();
So as a demo, consider the following example:
$('tr.selected').each(function() {
var ids = $(this).nextUntil('.selected').map(function() {
return $(this).data('id');
}).get();
console.log( ids );
});
.selected {
background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1">
<tr data-id="1"><td>Row 1</td></tr>
<tr data-id="2" class="selected"><td>Row 2</td></tr>
<tr data-id="3"><td>Row 3</td></tr>
<tr data-id="4"><td>Row 4</td></tr>
<tr data-id="5" class="selected"><td>Row 5</td></tr>
<tr data-id="6"><td>Row 6</td></tr>
<tr data-id="7"><td>Row 7</td></tr>
</table>
Update Code working Here
I have a table populated with teacher's disciplines that has: day of the week and it's time period, of course it also have the disciplines.
Now I need to remove those items.
Table:
<table id="prof-table">
<tbody><tr>
<th>HORÁRIO</th>
<th data-dia="mon">Monday</th>
<th data-dia="tue">Tuesday</th>
<th data-dia="wed">Wednesday</th>
<th data-dia="thu">Thursday</th>
<th data-dia="fri">Friday</th>
</tr>
<tr>
<td>08:30 ~ 10:30</td>
<td><ol><li data-id="6" data-prof="4">Calculo A</li></ol></td>
</tr>
<tr>
<td>10:30 ~ 12:30</td>
td></td><td><ol><li data-id="2" data-prof="4">Lab II</li></ol></td>
</tr>
<tr>
<td>14:30 ~ 16:30</td>
</tr>
<tr>
<td>16:30 ~ 18:30</td>
</tr>
<tr>
<td>18:30 ~ 20:30</td>
<td></td><td></td><td></td><td></td><td><ol><li data-id="5" data-prof="4">Estatistica</li></ol></td>
</tr>
<tr>
<td>20:30 ~ 21:30</td>
</tr>
<tr>
<td>21:30 ~ 23:30</td>
</tr>
</tbody></table>
What I did so far is to get the <td> from the rows but I don't know how to work with it, tried to use .each() from JQuery but I just cant do it.
Javascript:
var myRow = document.getElementById("prof-table").rows[range.index + 1];
var test = $(myRow.getElementsByTagName('td')).not(':first-child');//Skip the first td because its the time period of the discipline.
console.log(teste);
Now if you check the console.log() this is what is shown:
As you can see, there are three lines. Each line/obj has the exactly number of <td>s from the row.
What I need to do is loop through each of these lines. Also I need to reset the index for each loop.
EX: While interacting with the first line of the image, my Index goes from 0 ~ 1. Then when start the second line I need to start my index from 0 again untill 4 (because it has 5 elements td)
Tried something like:
$.each(teste, function(index, obj){
if($(obj).text() == "")
myRow.deleteCells(index);
});
But as the index doesnt "reset" for each of those lines in the picture, I get error about overflowing the row index limite. Because while the first row has only one <td> member, the last has 5, as the index is always growing ++ I get that error. And I have no idea how to work around it.
Because I don't understand you situation well, I create two function
To delete data based on "data-prof" attribute of "li" inside the "td"
To delete all data of the table.
In my oppinion, if you assign "data-prof" value to the "td" instead of "li", it'll boost performance.
Hope it's help.
Function to delete data based on "data-prof" attribute:
function resetTableData(dataProf) {
// Get cell list by data-prof
var $cellList = $("#prof-table").find("li[data-prof = " + dataProf + "]").closest("td");
$cellList.each(function(){
$(this).html(""); //Remove inner HTML of cells.
});
}
Function to delete data of all cells:
function resetTableData() {
// Get row list
var $rowList = $("#prof-table").find("tr").not(":first"); // First row is the header, don't need to select.
// Loop row list and get cell list of each
$rowList.each(function(){
// Cell list
var $cellList = $(this).find("td").not(":first"); // First column is time period, don't delete it.
// Loop cell list and delete content
$cellList.each( function() {
$(this).html(""); //Remove inner HTML of cells.
});
});
}
I have a table, which looks like this:
<table id="ctoTable" class="table table-bordered">
<thead> ... </thead>
<tbody>
<tr></tr>
<tr id="kpi#1" class="js-editable"></tr>
<tr id="kpi#2" class="js-editable"></tr>
<tr id="kpi#3" class="js-editable"></tr>
<tr id="kpi#4" class="js-editable"></tr>
<tr id="kpi#5" class="js-editable"></tr>
<tr id="kpi#6" class="js-editable"></tr>
<tr id="kpi#7" class="js-editable"></tr>
<tr id="kpi#8" class="js-editable"></tr>
<tr id="kpi#9" class="js-editable"></tr>
<tr id="kpi#76" class="js-editable"></tr>
<tr id="kpi#77" class="js-editable"></tr>
<tr></tr>
</tbody>
and I would like to be make some kind of filter which allows me to show and hide some of the rows. I was pretty sure that I could do it on this way but unfortunately it does not work. Not only that I am not able to add/remove classes, I can't event get an attribute of an th.
jQuery(document).ready(function($) {
$( "#hideRows" ).click(function() {
var rows = $('.js-editable');
$.each(rows, function(index, item) {
console.log(item);
//item.addClass("hideElement"); //try to add the class to the tr
console.log(item.attr("id")); //try to print tr id in console
});
});
});
as a result only the first row will be printed out
<tr id="kpi#1" class="js-editable"></tr>
and than the method breaks without any errors logged.
Could someone expain to me what is happening here and how could I fix this issue.
The problem is item inside the loop is a dom element reference not a jQuery object so you can't access jQuery methods directly from item.
Instead you need to get a jQuery object reference for item by passing it to jQuery like $(item) and then you can use jQuery methods like
jQuery(document).ready(function ($) {
$("#hideRows").click(function () {
var rows = $('.js-editable');
rows.each(function (index, item) {
console.log(item);
//$(item).addClass("hideElement"); //try to add the class to the tr
console.log($(item).attr("id")); //try to print tr id in console
});
});
});
But if you just want to add a class there is no need to use a loop
jQuery(document).ready(function ($) {
$("#hideRows").click(function () {
var rows = $('.js-editable');
rows.addClass("hideElement");
});
});
Also note then it is better to use .each() instead of $.each() to iterate over jQuery object.
If you write item.attr, it will return an error, because, by this way item is not a jQuery object.
Change it like this:
$(item).attr("id")
console.log($(item).attr("id")) instead of console.log(item.attr("id"))
jQuery(document).ready(function($) {
$( "#hideRows" ).click(function() {
var rows = $('.js-editable');
$.each(rows, function(index, item) {
console.log(item);
//item.addClass("hideElement"); //try to add the class to the tr
console.log($(item).attr("id")); //try to print tr id in console
});
});
});
DEMO