jQuery: Get <td>'s html only - javascript

i have this code. It returns all the td code including the td /td tags. I want it to only return the content/html of the td
<td>Hey</td>
should give me just
Hey
jQuery("#ReportTable", html).each(function (index, tr) {
arr[index] = jQuery("tbody tr", tr).map(function (index, td) {
return jQuery(td).html();
});
});
The jQuery code gives me an array looking like this:
arr[0] = {"<td>1</td>", "<td>Hey</td>", "<td>Some data</td>" }
arr[1] = {"<td>2</td>", "<td>There</td>", "<td>Some other data</td>" }
From html looking like this:
<table id="ReportTable"><tr><td>1</td><td>Hey</td><td>Some data</td></tr><tr><td>2</td><td>There</td><td>Some other data</td></tr></table>
So the array is good except that i only need the html / text inside the td's.

You need to go down one more level in your selector, like this:
jQuery(".ReportTable", html).each(function (index, tr) {
arr[index] = jQuery("tbody tr td", tr).map(function (index, td) { return jQuery(td).html(); });
});
Or, just use .text() instead or .html(), like this:
jQuery(".ReportTable", html).each(function (index, tr) {
arr[index] = jQuery("tbody tr", tr).map(function (index, td) { return jQuery(td).text(); });
});
(I have ".ReportTable" instead of "#ReportTable", as comments noted on the question IDs need to be unique...so you should use class="ReportTable" if there are multiple)

It seems to me that the simplest solution would be to work directly on the TDs instead of selecting their parent first. Does the code below solve the problem? (I could have mis-understood - apologies if that's the case!)
jQuery("#ReportTable td", html).each (function (index) {
arr[index] = jQuery(this).html();
}

So why not select the TD instead of the TR in your selector and work from there? jQuery's html() function leverages htmlElement.innerHtml, so you shouldn't have any problems once you select the correct elements.

Related

jQuery value returned from text() causes unrecognised expression error when adding to array

I have the following code:
$(document).ready(function () {
debugger;
// Empty aarray to store list of headings
var tableHeadings = [];
// For each heading present add it to the array (ordered)
$('#AdvancedTable thead > tr > th').each(function () {
//console.log($(this).text());
$(tableHeadings).add($(this).text());
});
// For each row in the table, add the heading text to the start of each cell
$('#AdvancedTable tbody > tr > td').each(function (index) {
$(this).prepend('<span class="visible-xs">' + tableHeadings[index] + '</span>');
})
});
However, one of my table headings I am storing values from contains the text "Length (L1)". I get the following error in my console:
Uncaught Error: Syntax error, recognised expression: Length (L1)
I understand the basics that this is caused by there being issues with text passing something with brackets in it, but would like to know the details of why this happens and a hint as to how I can solve this/best practices to avoid an error like this.
Use map instead of each.
// Empty aarray to store list of headings
var tableHeadings = $('#AdvancedTable thead > tr > th').map(function () {
return this.innerHTML;
}).get();
You are creating an empty array, iterating over elements, and adding them to an array. This is essentially reinventing the wheel for what map already does.
tableHeadings is a simple array, so you can use push function to add value:
$(document).ready(function () {
let tableHeadings = [];
$('#AdvancedTable thead > tr > th').each( (index, item) => {
tableHeadings.push($(item).text())
});
$('#AdvancedTable tbody > tr > td').each( (index, item) => {
$(item).prepend('<span class="visible-xs">' + tableHeadings[index] + '</span>');
})
});
$(tableHeadings).add($(this).text());
need to be
tableHeadings.push($(this).text())
Not sure why you're using JQuery to add an item to a list; perhaps try:
tableHeadings.push($(this).text());
instead of the original line:
$(tableHeadings).add($(this).text());

Delete rows from table recursively using JQ

I want to write a recursive function that will delete rows from my table.
I have the number of rows to keep and after that number i want to remove all rows.
for example:
I have the number 5 so the first 5 rows need to stay and the rest need to go. (using the row id)
code:
<table id="table">
<tr id="tr1"/>
<tr id="tr2"/>
<tr id="tr3"/>
<tr id="tr4"/>
<tr id="tr5"/>
<tr id="tr6"/>
<tr id="tr7"/>
<tr id="tr8"/>
</table>
I dont know how much rows i will have, thats why i think i need a recursive solution.
You can use several different jQuery filter approaches:
var numRows=5;
$('#table tr').slice(numRows).remove();
OR
$('#table tr:gt(' + (numRows-1) + ')').remove();
DEMO
References:
slice() docs
:gt() selector docs
You can use this
$(document).ready(function(){
var deleteAfter = 5
$.each($("#table tr"),function(key,value){
//do your conditional here
if(key > deleteAfter-1){
value.remove();
}
});
alert("now the table row is "+$("#table tr").length);
});
This is working jsfiddle
I'm sorry if u want to using id as the input please use this instead
$(document).ready(function () {
//define the id first
var deleteAfter = $("#tr5");
var elementNo;
$.each($("#table tr"), function (key, value) {
if (this.id == deleteAfter.attr("id")){
elementNo = key;
}
});
$.each($("#table tr"), function (key, value) {
//do your conditional here
if (key > elementNo) {
value.remove();
}
});
alert("now the table row is " + $("#table tr").length);
});
And i updated the jsfiddle
you can use :gt() selector, it selects all the elements greater than index and then you can remove it.
$(document).ready(function () {
var index = 4; // set index 4, so want to remove 5 elements( 0 to 4)
$('#table tr:gt('+index+')').remove();
});

How to iterate over htmlCollection

I'm having some difficulty with this. In Backbone, I have a function like this:
functionOne: function(){
$('#myTExtbox-' + budgetLine.attr('id')).on('change keyup paste', function(){
that.mySecondFunction(this);
});
}
In this case, the this is a textbox, which is in a table, inside a div. Then:
mySecondFunction: function(tb){
var tbody = tb.parentElement.parentElement.parentElement.parentElement.parentElement;
//gets main parent, which is a tbody, inside a table, inside a div
}
I then want to iterate over tbody, to go through each row and find a textbox in a specific cell. The problem is that this code:
$.each(tbody, function(index, item){
cost = item;
var t= index;
});
Doesn't seem to allow me to get to any of the items. In this example, if I try to do something like:
item.getElementById('test');
I get an error:
TypeError: Object #<HTMLCollection> has no method 'getElementById'
Why can't I iterate over this object and access objects within?
Thanks
UPDATE
Here's a fiddle: http://jsfiddle.net/HX8RL/14/
Essentially, what should happen is this: When a text box changes, I want to iterate over all the rows in the tb's parent table and sum all the Tb values. Keeping in mind, all the tb's in the same cell position, as there could be other tb's in other places that I dont want to include.
There wont be any collection of TBody
try using children() instead
$.each(tbody.children('tr'), function(index, item){
cost = item;
var t= index;
});
Demo Fiddle
Iterate over all input elements directly to get values.
var tbody = tb.parentElement.parentElement.parentElement;
alert(tbody.id);
var input = $('#tbody').find('input');
alert(input);
console.log(input);
for (var i = 0; i < input.length; i++) {
alert(input[i].value);
alert(i);
}
See fiddle-http://jsfiddle.net/HX8RL/18/
I think there are a few things going wrong here. You know you can only have one ID per page? So you have to do document.getElementByid('test') instead.
Since you are also using jQuery you can use the find function, item.find('#test'). But I think this wouldn't solve you problem. Not sure what you want to achieve, maybe I can help you if you explain a bit more in detail what your problem is.
Also
tb.parentElement.parentElement.parentElement.parentElement.parentElement;
can be written as (in jQuery)
$(tb).parents('tbody');
I've setup a fiddle, maybe it can help you.
Code used in fiddle:
var myFuncs = (function() {
function funcA() {
$('input').on('keyup', function() {
funcB(this);
});
}
function funcB(myInput) {
var $table = $(myInput).parents('table');
$table.find('tr > td > input').each(function() {
var $input = $(this);
if($(myInput).attr('id') != $input.attr('id'))
$input.val("I'm called from another input");
});
}
return {
funcA : funcA
}
})();
myFuncs.funcA();

How to select a td from a table with id using jQuery

I have a table with td's with id. I need to select those td's and reorder the columns.
$('table tr').each(function () {
var tr = $(this);
var tds = $('#Status');
var tdA = $('#Address');
alert(tds.innerHtml); //Here am getting a blank msg
tds.remove().insertAfter(tda); //This is what i need to do
});
I found the answer:
var tds = tr.find("td[id='Status']"); //what i was looking for
Thanks for ur support and special thanks for voting my genuine question 2 points down :D, since iam not point hungry, No offense :-)
var selectedTd = $("#ID_OF_TD");
or to call the method like on click etc etc you can directly call the method
$("#ID_OF_TD").click(function(){
});
you need to put this code in document ready section ..
$("document").ready(function(){
$("#ID_OF_TD").click(function(){
alert('td clicked');
});
});
Simply do $("#idHere").
More Info: http://api.jquery.com/category/selectors/
Use Id Selector
$('#tdID')
//^# followed by html id
Using jQuery apply: $('#td_ID')
we can use :
$('table > tr > td#Status');
$('table > tr > td#Address');

JQuery .addclass to table <tr> element where text is found

I am theming some report tables and do not have access to the templates.
I have this code so far which ends up adding "my-class" to every TR element in the report table. However, I only want to add the class to the table row TR where the text was found. I am thinking I need a little more code to do this. Here are a few things I have tried so far:
if ($('#report-area table tr:contains("Name")', this).length > 0) {
$("#reportArea table tr", this).addClass("my-class");
}
I have also tried:
if ($('#report-area table tr:contains("Name")', this).length > 0) {
$(this).addClass("my-class");
}
... but that did not work either.
Just use the selector with no fluff:
$('#report-area tr:contains("Name")').addClass('my-class');
http://api.jquery.com/contains-selector/
var $rows = $('#report-area table tr');
$rows.each(function(i, item) {
$this = $(item);
if ( $this.text() == 'Name' ) {
$this.addClass('yourClass');
}
});
I only want to add the class to the table row TR where the text was
found.
You can do:
$('#report-area table tr').each(function(){
if ($.trim($(this).text()).length > 0) {
$(this).addClass("my-class");
}
});
You can also use the .filter() function as well here:
$(document).ready(function () {
$('#report-area tbody tr').filter(function () {
return $.trim($(this).text()).length > 0;
}).addClass("my-class");
});
I like this because it's a little cleaner and limits the number of rows you need to iterate over.

Categories

Resources