Using JQuery .append() to dynamically change table layout - javascript

I am using an HTML table but I want to dynamically change the layout of the table based on the browser size. My basic code looks like this:
<tr>
<td class="row">E1</td>
<td class="row">E2</td>
<td class="row">E3</td>
<td class="lastRow">E4</td>
</tr>
Then the JQuery should calculate the number of rows and insert row-breaks accordingly.
My JQuery looks like this for now:
$('td.row').append('</tr><tr>');
Yet, its still displaying all the elements on one line. Any idea why?

This is a perfect place to use fluid CSS layouts.
Instead of writing lots of crazy Dom-manipulating javascript, simply replace your TD tags with divs and have them float:left
Further- append does not do what you think it does. It's dom manipulation and not string manipulation- you can't use it to directly change HTML the way you're thinking.
Further reading

Try looking at .after(); function:
http://api.jquery.com/after

i think that you need to try with this selector
Asumming that your table haved an id called example try like this
$("#exmaple tr:last").append('<tr></tr>');

$('</tr><tr>').insertAfter('.row');

You'd want to do your append on the tr element, not on td.row

You need to not think in terms of constructing HTML markup. There's no way to splice a closing/opening </tr><tr> into the DOM (without some ugly .innerHTML hacks).
Instead, create a new row after the current row, and the relocate the cells into that new row.
var row_cells = $('td.row').slice(1);
row_cells.each( function( i, el ) {
$('<tr>').insertAfter( row_cells.eq(i).parent() )
.append( row_cells.eq(i) );
});
DEMO: http://jsfiddle.net/EDf5a/
Or maybe you wanted a new row for each cell:
var row_cells = $('td.row');
var row = row_cells.parent();
row_cells.each(function(i, el) {
$('<tr>').insertBefore(row)
.append(row_cells.eq(i));
});
DEMO: http://jsfiddle.net/EDf5a/1/

Related

Edit HTML Table Data cell using Jquery

I have an HTML table, and each cell of the table will have two data attributes. What I'm trying to do is set a button to switch the value being shown in the table between those two attributes.
<table class="table1">
<tbody>
<tr>
<td data-original="A" data-new="B"> A </td>
</tr>
</tbody>
</table>
I'm able to set new text and get attributes outside the table, but whenever I try to within the table I keep receiving an error:
'Uncaught -> TypeError: undefined is not a function'.
I've been receiving this error for a number of commands $('td').text(), .val(), .attr('td'), .getAttribute().
Am I missing a plugin or something for getting and setting values from tables?
ANSWER: I figured out the reason, I was an idiot and didn't mention that there would be numerous TD elements with repeating tags. I eventually used Underscore.js's each method to iterate through them and parts of the below answer to swap the values.
Just made a Fiddle:
$("button").on("click", function () {
$("td").text($.trim($("td").text()) == $("td").data("original")
? $("td").data("new") : $("td").data("original"));
});
to switch between the data-original and data-new values by checking the current text in the td and using a ternary operator.
By using trim() for the initial text issues in case of whitespace are taken care of (as I just noticed that you have whitespace in your example td).
Just in case the button isn't already in the DOM when the page is initially loaded, you have to adjust the on() to delegate the click event from a static parent element to the button, e.g. like this: $(document).on("click", "button", function () { ...
Instead of $(document) every other static parent element can be used.
And as you mentioned that the table will have multiple tds with data-attributes, I've just adjusted the Fiddle to take care of that:
$("button").on("click", function () {
$("td").each(function () {
$(this).text($.trim($(this).text()) == $(this).data("original") ?
$(this).data("new") : $(this).data("original"));
});
});
I don't know how .text() didn't work for you.
To set text inside td elements, you use .text(). To get the data inside data-current or data-new, jQuery has a handy function .data(tag), for example $(sel).data('current').
Here's a fiddle displaying usage of this on your problem.

How to select cell using jQuery id selector

I am getting ID of table cell using the following Javascript
var tempCell = e.target.parentNode.id;
Now I have to append a table in tempCell using jQuery like that
var htmlToAppend = '<table id="tbleSelectApproovers"></table>';
$(???).append(htmlToAppend);
I am not sure how to write the syntax to use id for the purpose to add table in td. What to write in place of question mark to add table in tempCell
You have to give id to td in id selector. Before id you need to give #
$('#idoftd').append(htmlToAppend);
If you can get the element by e.target.parentNode then you can pass it to jQuery method to make jQuery object out of it.
$(e.target.parentNode).append(htmlToAppend);
use escaping rule from selector http://api.jquery.com/category/selectors/
$('#e\\.target\\.parentNode\\.id').append(htmlToAppend);
or
$('[id="e.target.parentNode.id"]').append(htmlToAppend);
update:
$('#'+e.target.parentNode.id).append(htmlToAppend);
or
$('#'+tempCell ).append(htmlToAppend)
From the looks of it you are trying to append the element to the current elements parent so
var htmlToAppend = '<table id="tbleSelectApproovers"></table>';
$(e.target.parentNode).append(htmlToAppend);
easy way : keep an id or class attribute to the table cell like for example say
<td id="tablecellid">
now if you want to append anything keep it in a variable for readability
var data = ''
and do the following
$("#tablecellid").append(data);
Assuming your cell looks like this:
<td id='myfavcell'></td>
you would call
$('#myfavcell').append(htmlToAppend);
as jquery uses the css selector type (#) for locating element IDs.

Use Jquery to find the parent table, of a table, of a td

I am customising Sage CRM, so I have no control over the HTML that is written and can't add IDs or class's to the table layouts the CRM spits out. I want to hide a higher (not top) level table based on a users selection of a select dropdown. I can only get a jQuery selector hooked onto the title row of a table within the table I want to hide.
The DOM goes something like:
//Lots of other table structures above this in the DOM....
<table> <---- this is the table I want to show or hide based on the users selection
<tbody>
<tr>
<td>
<table>
<tbody>
<tr>
<td class="PANEREPEAT"> <---- this is the node I can get selector to
Valuation information
////
So I do the below client side javascript:
var val_information_screen;
$('.PANEREPEAT').filter(function () {
//Find the valuation information screen
return $(this).text() == 'Valuation information';
}).each(function () { //iterate through all of these (there should only be one!)
val_information_screen = $(this);
});
var sel_ofee_type = $('#ofee_type');
if (sel_ofee_type.val() == '006') {
val_information_screen.closest('table').parents("table:first").show();
} else {
val_information_screen.closest('table').parents("table:first").hide();
}
It does work, it just is not particularly beautiful. The bit that I really detest is below. Is there a better way to traverse up the DOM using jQuery?
val_information_screen.closest('table').parents("table:first").show();
val_information_screen.closest('table').parents("table:first").hide();
If you are sure that it has fixed structure, then you can use this,
$(td-selector).parents("table").eq(1).hide();
In your case,
val_information_screen.parents("table").eq(1).hide();
If your DOM (specifically starting from table you want to hide till the td you have as selector) is pretty much fixed, then the below selector can be used.
$('#element').parents('table').eq(1)

jQuery How to Target A String in a TD Class

I'm trying to subtract a two characters from a string that is being dynamically generated from a database that is being placed into a shopping cart table td. So instead of having a product show as $28.00, I want the product to show up as $28. Since these values are coming from a database, I can't simply define the string in a variable, like I've seen in a lot of tutorials.
Here's my JS Fiddle
http://jsfiddle.net/EbckS/6/
Here's my eronous code
$(document).ready(function(){
$("table td.SCNProductPrice").text(function(i, text) {
return text.slice(0, -2);
});
});
This is a follow up to a different question I posted here:
jQuery Removing last two characters in a class
I'm placing this into a different question because I didn't realize targeting a class within a table td would require different syntax. Thanks for your help!
Assuming your html is valid i.e it has table and td your slice has wrong index. First one will take care of any number of decimal points if at all comes up.
try
$("table td.SCNProductPrice").text(function(i, text) {
return '$' + parseInt(text.replace('$',''));
});
or
$("table td.SCNProductPrice").text(function(i, text) {
return text.slice(0, -3);
});
You should add td inside a tr which is inside a table.
<table>
<tr>
<td class="SCNProductPrice" valign="top">$28.00</td>
</tr>
</table>
Demo
Markup:
<table>
<tr>
<td class="SCNProductPrice" valign="top">$28.00</td>
</tr>
</table>
JS:
$(document).ready(function(){
$("td.SCNProductPrice").text(function(i,text) {
return text.split('.')[0];
});
});
don't forget, you need valid markup during your fiddle. lastly, i'm not sure why you'd want "$28." shouldn't it just be "$28" ? The JS above does the latter.

remove parent container

I have a form with the fields inside table cells. On the last column of each line I have an image. When clicking that image I want to delete the parent <tr>. Before I tried to do it by generating a function passing as the argument the line number: onclick='delete_row(x, y)'. This is obviously not a good solution since I was deleting the row by its position. The function I'm calling has other 2 arguments since it deletes the row in the database too, so the second argument is the id in the database to delete. So basically I need a function that deletes the parent <tr> and that accept some other arguments too.
EDIT Thanks:
Thank you all guys, I tried almost all the solutions and all worked nice. I just decided for the Mike's Samuel one, it seemed the easiest :) Thanks again
To pass the grandparent of the current node use this.parentNode.parentNode:
<tr><td><img onclick="delete_row(this.parentNode.parentNode, ...)"></td></tr>
How about removing the closest <tr>? You would need to make accommodations for the selectors that are present in your code, but the general form looks like this:
$('img').click(function(){
$(this).closest('tr').remove();
});
You could easily use the HTML node method .removeChild() and traverse through the node's .parentNodes: (demo):
<td onclick="this.parentNode.parentNode.removeChild(this.parentNode);">
Remove row
</td>
this.parentNode.parentNode will be the <table> or <tbody>, while this.parentNode is the parent container <tr>.
Update: rjz provided a neat function (demonstration):
window.removeClosestRow = function(node) {
while(node = node.parentNode) {
if (node.tagName.toUpperCase() == 'TR') {
node.parentNode.removeChild(node);
break;
}
}
}
try something like
onClick='MyDeleteFunc(this, var2, var3)';
that will pass the actual object you're clicking on to javascript, and you can get pretty much all your references from there.

Categories