How to insert markup into a table using javascript - javascript

I have a table row with four cells. I'm trying to use javascript to insert this:
</tr><tr>
in between two cells which would basically create two rows from one (at certain screen sizes).
I need to change this:
<table>
<tr>
<td>stuff</td>
<td>stuff</td>
<td>stuff</td>
<td>stuff</td>
</tr>
</table>
into this:
<table>
<tr>
<td>stuff</td>
<td>stuff</td>
</tr><tr>
<td>stuff</td>
<td>stuff</td>
</tr>
</table>
Here is my script:
$('table tr td:nth-child(3)').before('</tr><tr>');
And here is what I get:
<table>
<tr>
<td>stuff</td>
<td>stuff</td>
<tr></tr> <--- notice that </tr><tr> becomes <tr></tr>!
<td>stuff</td>
<td>stuff</td>
</tr>
</table>
The tags are appearing in the right place, but they are switched around!
What the heck is going on here? Can anyone please help?

Despite the abstraction offered by jQuery, you are not working with HTML. You are working with DOM objects.
"</tr><tr>" gets interpreted as:
End tag for table row which doesn't exist, ignore this
Create a table row
You need to create a table row, put it where you want it to be and then move the table cells into it.
Possibly like this:
var tr = $('<tr />');
tr.append($('td+td+td'));
$('table').append(tr);

You could add another row and transfer the last two td elements to the new row.
$('<tr>').insertAfter('tr').append($('td').slice(-2))
http://jsfiddle.net/g9xnsus5/2/

Related

Adding <td> to one row of table but not all changes row position

I have a table like this
<table>
<tr>example1</tr>
<tr>example2</tr>
<tr>example3</tr>
</table>
and it works fine but if I add <td> to the first row and not the others it goes straight to the bottom - http://jsfiddle.net/sLd1L92t/1/
<table>
<tr><td>example1</td></tr>
<tr>example2</tr>
<tr>example3</tr>
</table>
Is there any way I can have the <td> in just one row and not have that row repositioned?
Add a <td> to each row, like so:
<div>
<table border="1">
<tr><td>example1</td></tr>
<tr><td>example2</td></tr>
<tr><td>example3</td></tr>
</table>
</div>
(I added a border to make it clear where the cell boundaries are)
And if you want the second two rows to fill the width of the table, then use colspan which tells the row to span multiple columns:
<div>
<table border="1">
<tr><td>exampleA</td><td>exampleB</td></tr>
<tr><td colspan="2">example2</td></tr>
<tr><td colspan="2">example3</td></tr>
</table>
</div>
Adding in the <td> is correct HTML, so I don't believe there is a way to do what you want.
Why are you trying to write the table that way? You can probably make it work using <div> tags instead.

jQuery.after won't accept </tr> to end an element after starting one

I have a table that is generated by some other software, each row contains 50 columns and I'm trying to break the columns by adding a </tr><tr> to the end of a <td> element.
This is the code that is generated on the fly:
<tbody>
<tr>
<td class="col1" scope="col">08/22/2014</td>
<td class="col2" scope="col">Share</td>
<td class="col3" scope="col">Success</td>
<td class="col4" scope="col">Some notes</td>
<td class="col5" scope="col">8/23/2014</td>
...etc
<td class="col51" scope="col">End column</td>
If I use this Jquery:
$( ".col4").after('</tr><tr><td> </td>');
It appends but doesn't respect the </tr>....it ignores it and adds the <tr> on, resulting this code.
<td class="col3" scope="col">Success</td>
<td class="col4" scope="col">Some notes</td>
<tr>
<td> </td>
</tr>
<td class="col5" scope="col">etc...</td>
Wonder what the best way to get JQUERY to append that <TR> for me? When I modify the code in Firebug, breaking the rows gives me the desired output, just not sure how to get JQUERY to give me the </tr>.
jsFiddle Example
Detach the last 2 cells, append them to tbody and wrap them with tr
$('.col4').nextAll().detach().appendTo('tbody').wrapAll('<tr />')
You cannot insert tags separately using JQuery. For instance, take the following code, which inserts a <p> element into the body:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script>
$("body").append("<p>");
</script>
</body>
</html>
Using the Firefox inspector, this is what the DOM looks like:
Thus, $("...").append("<p>"), $("...").append("</p>"), $("...").append("<p></p>") all modify the DOM in the same way.
You cannot handle incomplete or illegally formatted HTML as DOM elements. You want to gather up the correctly formatted children before that column and stuff them into a new complete <tr>.
If you want to handle HTML as text, you need to turn it into text with html() and paste it together into actual, correctly closed HTML, and then convert it back.

Show/Hide Table Rows using Javascript classes

I have a table that kind of expands and collapses, but it's getting too messy to use it and IE and Firefox are not working properly with it.
So, here's the JavaScript code:
function toggle_it(itemID){
// Toggle visibility between none and ''
if ((document.getElementById(itemID).style.display == 'none')) {
document.getElementById(itemID).style.display = ''
event.preventDefault()
} else {
document.getElementById(itemID).style.display = 'none';
event.preventDefault()
}
}
And a Sample HTML:
<table>
<tr>
<td>Product</td>
<td>Price</td>
<td>Destination</td>
<td>Updated on</td>
</tr>
<tr>
<td>Oranges</td>
<td>100</td>
<td>+ On Store</td>
<td>22/10</td>
</tr>
<tr id="tr1" style="display:none">
<td></td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr id="tr2" style="display:none">
<td></td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
<tr>
<td>Apples</td>
<td>100</td>
<td>+ On Store</td>
<td>22/10</td>
</tr>
<tr id="tr3" style="display:none">
<td></td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr id="tr4" style="display:none">
<td></td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
</table>
The problem is that I use one ID for each and every and that's very annoying because I want to have a lot of hidden rows for each parent and a lot of parents, so it would be too many IDs to handle. And IE and FireFox are only showing the first Hidden Row and not the others. I suspect this happens because I've made it work by triggering all IDs together.
I think it would be better if I use Classes instead of IDs to indetify the hidden rows.
I'm really new to all of this so please try and explaining it in any kind of simply way. Also I've tried jQuery but wasn't able to get it.
It's difficult to figure out what you're trying to do with this sample but you're actually on the right track thinking about using classes. I've created a JSFiddle to help demonstrate a slightly better way (I hope) of doing this.
Here's the fiddle: link.
What you do is, instead of working with IDs, you work with classes. In your code sample, there are Oranges and Apples. I treat them as product categories (as I don't really know what your purpose is), with their own ids. So, I mark the product <tr>s with class="cat1" or class="cat2".
I also mark the links with a simple .toggler class. It's not good practice to have onclick attributes on elements themselves. You should 'bind' the events on page load using JavaScript. I do this using jQuery.
$(".toggler").click(function(e){
// you handle the event here
});
With this format, you are binding an event handler to the click event of links with class toggler. In my code, I add a data-prod-cat attribute to the toggler links to specify which product rows they should control. (The reason for my using a data-* attribute is explained here. You can Google 'html5 data attributes' for more information.)
In the event handler, I do this:
$('.cat'+$(this).attr('data-prod-cat')).toggle();
With this code, I'm actually trying to create a selector like $('.cat1') so I can select rows for a specific product category, and change their visibility. I use $(this).attr('data-prod-cat') this to access the data-prod-cat attribute of the link the user clicks. I use the jQuery toggle function, so that I don't have to write logic like if visible, then hide element, else make it visible like you do in your JS code. jQuery deals with that. The toggle function does what it says and toggles the visibility of the specified element(s).
I hope this was explanatory enough.
Well one way to do it would be to just put a class on the "parent" rows and remove all the ids and inline onclick attributes:
<table id="products">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Destination</th>
<th>Updated on</th>
</tr>
</thead>
<tbody>
<tr class="parent">
<td>Oranges</td>
<td>100</td>
<td>+ On Store</td>
<td>22/10</td>
</tr>
<tr>
<td></td>
<td>120</td>
<td>City 1</td>
<td>22/10</td>
</tr>
<tr>
<td></td>
<td>140</td>
<td>City 2</td>
<td>22/10</td>
</tr>
...etc.
</tbody>
</table>
And then have some CSS that hides all non-parents:
tbody tr {
display : none; // default is hidden
}
tr.parent {
display : table-row; // parents are shown
}
tr.open {
display : table-row; // class to be given to "open" child rows
}
That greatly simplifies your html. Note that I've added <thead> and <tbody> to your markup to make it easy to hide data rows and ignore heading rows.
With jQuery you can then simply do this:
// when an anchor in the table is clicked
$("#products").on("click","a",function(e) {
// prevent default behaviour
e.preventDefault();
// find all the following TR elements up to the next "parent"
// and toggle their "open" class
$(this).closest("tr").nextUntil(".parent").toggleClass("open");
});
Demo: http://jsfiddle.net/CBLWS/1/
Or, to implement something like that in plain JavaScript, perhaps something like the following:
document.getElementById("products").addEventListener("click", function(e) {
// if clicked item is an anchor
if (e.target.tagName === "A") {
e.preventDefault();
// get reference to anchor's parent TR
var row = e.target.parentNode.parentNode;
// loop through all of the following TRs until the next parent is found
while ((row = nextTr(row)) && !/\bparent\b/.test(row.className))
toggle_it(row);
}
});
function nextTr(row) {
// find next sibling that is an element (skip text nodes, etc.)
while ((row = row.nextSibling) && row.nodeType != 1);
return row;
}
function toggle_it(item){
if (/\bopen\b/.test(item.className)) // if item already has the class
item.className = item.className.replace(/\bopen\b/," "); // remove it
else // otherwise
item.className += " open"; // add it
}
Demo: http://jsfiddle.net/CBLWS/
Either way, put the JavaScript in a <script> element that is at the end of the body, so that it runs after the table has been parsed.
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("tr1").show();
$("tr1").hide();
w3cSchool link to JQuery show and hide
event.preventDefault()
Doesn't work in all browsers. Instead you could return false in OnClick event.
onClick="toggle_it('tr1');toggle_it('tr2'); return false;">
Not sure if this is the best way, but I tested in IE, FF and Chrome and its working fine.
Below is my Script which show/hide table row with id "agencyrow".
<script type="text/javascript">
function showhiderow() {
if (document.getElementById("<%=RadioButton1.ClientID %>").checked == true) {
document.getElementById("agencyrow").style.display = '';
} else {
document.getElementById("agencyrow").style.display = 'none';
}
}
</script>
Just call function showhiderow()upon radiobutton onClick event
AngularJS directives ng-show, ng-hide allows to display and hide a row:
<tr ng-show="rw.isExpanded">
</tr>
A row will be visible when rw.isExpanded == true and hidden when
rw.isExpanded == false.
ng-hide performs the same task but requires inverse condition.

DIV and tables - multiple rows

I am trying to put a div inside of a table however, it will not go across multiple rows.
Here is the code I am using:
<table>
<tr>
<td><div id="test"></td>
</tr>
<tr>
<td>row 2 stuff</td></td>
</div>
</table>
I have multiple rows that are dynamically added on a button click. I would like each group of dynamically added rows to be inside of a div for easy removal.
The problem is FireFox is automatically closing the div tag in the same cell. At the very end, it is moving my closing to the end of the first cell.
Latest tag opened should be closed first to get the perfect result.
Your code should look somehow like this:
<table>
<tr>
<td><div id="test"></div></td>
</tr>
<tr>
<td>row 2 stuff</td>
</tr>
</table>
You cannot wrap a <div> tag around table elements like that. If you would like to keep an easy reference to each row, consider keeping references to all of the newly-added rows, or add a class to them for later access.
Your markup does not abide by html standards in the sense that you are imporperly nesting. If you want to add a row use the following formation
<table>
<div id="test">
<tr>
<td></td>
</tr>
<tr>
<td>row 2 stuff</td></td>
</tr>
</div>
</table>
If you notice, I grouped the two rows within one div. Even this is ill advised as you are nesting a div within a table. A more convenient solution would be to assign a class to the divs you want to group together like so:
<table>
<tr class="test">
<td></td>
</tr>
<tr class="test">
<td>row 2 stuff</td></td>
</tr>
</table>
Here the rows I want to group together are assigned a common class. So if I were to select them with say Jquery, I would do :
$("tr.test")
Hope that helps!
Html tags must be strictly within another tag. The following markup is therefore not allowed:
<b>this <i>is a</b> test</i>
Your markup breaks the same rule.

Looping through table rows with Javascript/Jquery

So what I'm trying to do is get the last row of an HTML table. If this row then has a certain class I will ignore this row and select the previous one. This would then be cycled through from the end of the table until a row was found without this certain class.
I figured it's probably involving a for loop, a check for the row class and then JQuery's row.prev method, but still not quite sure how to approach this.
Thanks in advance!
To get the last table row that doesn't have a certain class, say targetClass, you can do this:
$("tr:not(.targetClass):last");
I'm not sure what you want to do with this table row, but if you were to add targetClass to the last row that didn't have it, it would look like this
$("tr:not(.targetClass):last").addClass("targetClass");
Check out this fiddle to see it in action
This example shows you how to get the last of each table on the current page: http://jsfiddle.net/JBnzK/
$('table').find('tr:last').each(function(){
if ($(this).hasClass('stupid')) {
$(this).css('color', 'red');
} else {
$(this).css('color', 'green');
}
});
Assuming you've got the following HTML:
<table id="mytable">
<tbody>
<tr>
<td>1</td>
</tr>
<tr id="YouFoundMe">
<td>1</td>
</tr>
<tr class="certainclass">
<td>1</td>
</tr>
<tr class="certainclass">
<td>1</td>
</tr>
<tr class="certainclass">
<td>1</td>
</tr>
</tbody>
</table>
You can do this:
var elWithoutClass = $('#mytable tr:not(.certainclass):last');
if (elWithoutClass.length) {
alert(elWithoutClass.get(0).id);
// alerts "YouFoundMe"
}
:not(.certainclass) will eliminate <tr> without class 'certainclass'
:last will get you the last one
I invite you to check the Selectors documentation page of jquery to learn more about them.

Categories

Resources