wrap divs within 2x2 table jquery - javascript

I have four divs like below.
<div class='link'>...</div>
<div class='link'>...</div>
<div class='link'>...</div>
<div class='link'>...</div>
I want to place them in a 2x2 table.
<table>
<tr>
<td><div class='link'>...</div> </td>
<td><div class='link'>...</div> </td>
</tr>
<tr>
<td><div class='link'>...</div> </td>
<td><div class='link'>...</div> </td>
</tr>
with jquery on document ready
=======
Actually I need nX2 grid layout for those DIV's, so I made each two divs have same height using jquery.css. But on zoom+- that grid setting disturbed, so I thought table layout would be better, I found wrapping a solution but I don't know how to wrap divs within nX2 table.
// i tried below each at once, but four divs, four rows wrapping a single div, i need how to wrap first two divs in one row, and each div in one td , totally a table....
1st trial $( ".linkbox" ).wrap( "<tr></tr>" );
2nd trial $( ".linkbox" ).wrap( "<table></table>" );
3rd $( ".linkbox" ).wrap( "<td></td>" );

What you can do this: DEMO
var t = $(document.createElement('table'));
t.appendTo('#target');
var tr;
var counter=1;
$('.link').each(function(){
console.log(this);
if(counter%2!=0)
{
tr = $(document.createElement('tr'));
tr.appendTo(t);
}
var td = $(document.createElement('td'));
td.appendTo(tr);
$(this).appendTo(td);
counter++;
});
Output:
<table>
<tbody>
<tr>
<td><div class="link">1</div></td>
<td><div class="link">2</div></td>
</tr>
<tr>
<td><div class="link">3</div></td>
<td><div class="link">4</div></td>
</tr>
</tbody>
</table>
Improved Demo by #Ruko

jsBin demo
$(".link").wrapAll("<table/>").each(function(i) {
$(this).wrap("<td/>");
if(i%2) $(this).parent().prev().andSelf().wrapAll("<tr/>");
});
To explain the jQuery above:
$(".link").wrapAll("<table/>") wrap them all into a table.
Each still refers to the DIV so we can do an each and pass the i index value
$(this).wrap("<td/>") wrap every DIV inside a TD element,
After the above is done, our DIV is now inside a TD element, and if i%2 is truthy means that we're currently inside the loop looking ad the ODD index element, so target the TD parent, target the previous TD element also, add to collection back the self and wrap them both into TR.

try
$("div.link").replaceWith(function (i, val) {
return $("<td/>", {
"class": $(this).attr('class'),
text: val
});
});
$("td.link").each(function (i, val1) {
if (i % 2 == 0) {
$("td.link:eq(" + i + "),td.link:eq(" + (i + 1) + ")").wrapAll($("<tr/>", {
'class': 'trNew'
}));
}
});
$("tr.trNew").wrapAll("<table/>");
DEMO

Try this jQuery code:
var table = $('<table></table>').addClass('foo');
for(i=0; i<3; i++){
var row = $('<tr></tr>').addClass('bar');
var td1 = $('<td></td>').addClass('bartd');
var td2 = $('<td></td>').addClass('bartd');
row.append(td1);
row.append(td2);
var div="<div class='link'> hi div </div>";
td1.append(div);
td2.append(div);
table.append(row);
}
$('html').append(table);
http://jsfiddle.net/rfa7Lh3g/3/

Related

how to remove a TR which have a TD that contain specific text

I have the following markup which have SPAN >> Table >> TR >> TD:-
now i want to specify either using css or jquery to remove the TR which have a TD that contain the word "Question" inside <nobr> tag. so can anyone adivce how i can do so ? thanks
You can use filter to compare the exact text of the <nobr> element, then remove the closest <tr>
$("span table tr td nobr").filter(function() {
return $(this).text() === "Question";
}).closest("tr").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>
<table>
<tr>
<td>
<h3>
<nobr>Question</nobr>
</h3>
</td>
</tr>
<tr>
<td>
Untouched
</td>
</tr>
</table>
</span>
Try to use :has() selector along with :contains() selecor to achieve what you want,
$("tr:has(td nobr:contains('Question'))").remove();
DEMO
You can do it with jQuery as shown below:
$(document).ready(function(){
$('td').each(function(){
if($(this).find('nobr').text() === 'Question') {
$(this).closest('tr').remove();
}
});
});
It would have been helpful if you could provide HTML. I would have created fiddle but You can try below solution
Iterate tr in table and find the tr having
$("table.ms-formtable > tbody > tr").each(function(){
var text = $(this).find("td:first").find("nobr").text();
if(text === 'Question') {
$(this).remove();
}
});
http://jsfiddle.net/9tw2kfek/

jQuery- How to select a element with class name from a list of elements

I am using jQuery.
I want to select a cell from a table.
So I tried the following codes.
// First line works fine for me. I can get a list of columns at the correct target row.
var targetColumns = $(elemClicked).closest("tr").find("td");
// I want to get the cell with the class named "draftstatus". This line has problem. I cannot get what I want.
var targetCell = columnsAtTargetRow.$(".draftstatus");
The targetColumns inspected from browser looks like the following:
The 5th td above is my target cell.
I also try to use find() function. It won't work either because find() will start from next children level.
columnsAtTargetRow.find(".draftstatus"); // this does not work.
What functions should I used to get that cell within that "list of td".
Thanks in advance.
You just need to figure out which selectors to use.
var targetColumns = $(elemClicked).closest("tr").find("td");
this goes up the DOM to the "tr" and selects the tds. If the elemClicked is inside a td you can select the tds with closest("td"), and then use siblings(".draftstatus");
If the elemClicked is a td, then you can just use siblings(".draftstatus");
Here is some example code to help demonstrate some selectors. Hope this helps some and not confused you more.
$(function(){
//reference all cells with myclass class using filter
$("#table1 tbody td").filter(".myclass").addClass("red");
// click events for all tds reference the .target class cell using siblings
$("#table1 tbody td").on("click",function(e){
$(this).siblings(".target").toggleClass("red");
});
//items inside a table cell click event
$("#table1 tbody td a").on("click",function(e){
//toggle bold class
$(this).closest("td").siblings(".target").toggleClass("bold");
//prevent event from bubbling up
e.stopPropagation();
});
})
.red {
background-color:red;
}
.bold { font-weight:bold; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table border="1" id="table1">
<tbody>
<tr>
<td>foo</td>
<td>bar</td>
<td class="myclass target">value2</td>
<td>Two link</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
<td class="myclass target">value2</td>
<td>Two link</td>
</tr>
</tbody>
</table>
This is incorrect:
columnsAtTargetRow.$(".myclass");
This should be:
columnsAtTargetRow.find(".myclass");

Find out which row of table you've just moved

I want to make a table with dragabble and droppable rows which I can achieve with jquery ui, however I then want to update the number in first cell in each row to always correspond to the numerical order from the top down.
For example the table might start out like this:
<table id="myTableId">
<tbody>
<tr class="draggable droppable"><td>1</td><td>abc</td></tr>
<tr class="draggable droppable"><td>2</td><td>def</td></tr>
<tr class="draggable droppable"><td>3</td><td>ghi</td></tr>
</tbody>
</table>
After the user has dragged the rows about it may end up like this for example:
<table id="myTableId">
<tbody>
<tr class="draggable droppable"><td>2</td><td>def</td></tr>
<tr class="draggable droppable"><td>3</td><td>ghi</td></tr>
<tr class="draggable droppable"><td>1</td><td>abc</td></tr>
</tbody>
</table>
I then want to run a function to sort numbers in the first cells back into numerical order from the top down so that the html would change to look like this:
<table id="myTableId">
<tbody>
<tr class="draggable droppable"><td>1</td><td>def</td></tr>
<tr class="draggable droppable"><td>2</td><td>ghi</td></tr>
<tr class="draggable droppable"><td>3</td><td>abc</td></tr>
</tbody>
</table>
The rows have been moved but the row at the top still has the value 1 in the first cell, the second row still has the value 2 and so on...
I have found a JavaScript a function which counts the number of rows in a table, how can I write a JavaScript function to reorder the numbers 1,2 and 3 back into sequence in the first cells in the table?
<script>
var rows = document.getElementById('myTableId').getElementsByTagName('tbody')[0].getElementsByTagName('tr').length;
alert(rows);
</script>
For reference this is the jquery I am using to make the rows draggable and droppable:
$(function() {
$(".draggable").draggable( {
helper: function() { return "<div class='shadow'></div>"; },
start: moveShadow,
revert: true
});
function moveShadow(event, ui) {
var helper = ui.helper;
var element = $(event.target);
helper.width(element.width());
helper.height(element.height());
}
$(".droppable").droppable({
hoverClass: 'ui-state-active',
drop: function(event, ui) {
var target = $(event.target);
var draggable = ui.draggable;
draggable.insertBefore(target);
}
});
});
No need to count anything. Just run a loop and increment:
http://jsfiddle.net/isherwood/tLpjho9f/
var myCount = 1;
$('#myTableId tr.droppable').each(function() {
$(this).find('td').eq(0).text(myCount);
myCount ++;
});
You'll want to work that into the drop callback.

jQuery - change table cells position

how can I change via jquery the cells position from 1 2 to 2 1 ?
<table id='mytable'>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
$('#mytable tr td:eq(0)').appendTo('#mytable tr');
The JSFIDDLE.
If you want to change all the second td to first position in your table, then you can use:
$.each($('#mytable tr td:eq(1)'), function() {
$(this).insertBefore($(this).prev());
})
Actually, above code will not work if your table have more than one <tr> element, if that is the case then you need to use .find():
$('#mytable tr').find('td:eq(1)').each(function() {
$(this).insertBefore($(this).prev());
});
Fiddle Demo
References: .each() , .find() , .insertBefore() , .prev()
with append
http://jsfiddle.net/F7HmQ/1/
$(function(){
var td = $("td").first() ;
$("tr").first().append(td);
});

How to set the row id [ TR ] and column id [ TD] in displaytag?

I am using Displaytag to display the DataGrid. Now, I have to change the color of rows based on some calculation. Like if
the value of column3 + column4 > coulmn5 then the row color should be yellow
value of column3 + column4 < coulmn5 then the row color should be red
value of column3 + column4 = coulmn5 then the row color should be white
I think the only way to do this is by using getElementByID() method
Note: i don't want to consider the solution using getElementsByTagName()[index] , reason being later on the column ordering might change.
at present i am using the following code, which i want to change.
var rows = tbody.getElementsByTagName("tr");
Iterate the rows Object
var tdObj = rows[i].getElementsByTagName("td")[3]
First, I do not believe it is possible to set the ids on the td's or tr's in displaytag without modifying the source. This has not left my list of things to do, but for now I have a work around for you.
Instead of defining your table:
<display:table id='row' name="..." export="true" requestURI="">
<display:column property="usefulData" title="Useful data" sortable="true" />
... more columns ...
</display:table>
do this:
<display:table id='row' name="..." export="true" requestURI="">
<display:column title="Useful data" sortable="true" >
<span id='${row.usefulData}' class='css_class_selector'>${row.usefulData}</span>
</display:column>
</display:table>
Note the span wrapping the printed data. Now you can select the data relating printing inside your table, which is probably what you want; to select your data, as opposed to specifically selecting the td's and tr's.
An id would be one way to do it. Another would be setting a class on each td (so you can re-use the same class on each row). Then you'd iterate over the cells looking for the one with the right className. You can abstract this away into a getElementsByClassName function if you like.
A way to do it with less markup would be to keep a column-to-index lookup and use that to get the column number instead of iterating over cells on every row. You could get this information from classes on the header, or col elements. eg.:
<script type="text/javascript">
function check(table) {
// Work out which column is at which index
//
var columns= {};
var ths= table.tHead.rows[0].cells;
for (var i= ths.length; i-->0;)
if (ths[i].className.indexOf('column-')==0)
columns[ths[i].className.substring(7)]= i;
// Check each row
//
var rows= table.tBodies[0].rows;
for (var i= rows.length; i-->0;) {
var cells= rows[i].cells;
var a= +cells[columns.a].innerHTML;
var b= +cells[columns.b].innerHTML;
var sum= +cells[columns.sum].innerHTML;
var right= a+b==sum;
rows[i].className= right? 'right' : 'wrong';
}
}
</script>
<style>
.right { background: green; }
.wrong { background: red; }
</style>
<table id="t">
<thead>
<tr>
<th class="column-a">A</th>
<th class="column-b">B</th>
<th class="column-sum">Sum</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>
<button onclick="check(document.getElementById('t'));">Check</button>
Note using innerHTML to get the text content is a bit naughty, but it works OK for numbers as they cannot contain HTML special characters. For arbitrary text you would need an extract-text-content function.
Using rows/cells is preferable to getElementsByTagName. It's quicker, easier-to-read and you don't have to worry about nested tables.

Categories

Resources