I wish to construct a complete table using jQuery.
I try to learn or copycat from this question
Create table with jQuery - append
but no luck.
What I want to create is
<table>
<thead>
<tr>
<th>Problem 5</th>
<th>Problem 6</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
The jQuery code I created is
var $table = $('<table/>');
var $thead = $('<thead/>');
$thead.append('<tr>' + '<th>Problem 5</th>' + '<th>Problem 6</th>' + '</tr>';
$table.append(thead);
var $tbody = $('<tbody/>');
$tbody.append( '<tr><td>1</td><td>2</td></tr>' );
$table.append(tbody);
$('#GroupTable').append($table);
But it failed running.
Can anyone tell me why?
You are missing a right paren in your $thead declaration:
$thead.append('<tr>' + '<th>Problem 5</th>' + '<th>Problem 6</th>' + '</tr>');
^
and you aren't appending your variables correctly:
$table.append($thead);
^
$table.append($tbody);
^
Here's a working fiddle.
thead, tbody is undefined? $thead, $tbody?
$table.append(thead);
and
$table.append(tbody);
Related
I need to get the contents of all the cells in a row, combine them, and put them into a textarea. I think I need the .each() function, like:
$('table tr').each(function() {
$(this).find('td').text().appendTo(textarea); // not right
});
But I don't know how to combine the contents of each cell into one and then put it into the textarea.
Basically, I have a table like this:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</table>
And I want it to end up like this:
<textarea>
1,2,3,4
1,2,3,4
1,2,3,4
</textarea>
http://jsfiddle.net/qy1e7to6/33/
I really appreciate any help you can give. Thank you.
You're very close! For each iteration of the table row, you want to combine the sequence of characters for each cell with a , separator. At the end, you want a line break.
One way we can easily combine the text with a , separator is using an array and then joining the array
var chars = [];
// add characters here...
chars.join(',');
When we append, we can add the new line for the text:
var chars = [];
// iterate each cell and push to array to join later!
$(this).find('td').each(function(){
chars.push($(this).text());
});
// append to text area and join the array
textarea.append(chars.join(','), '\n');
Here's an updated fiddle:
http://jsfiddle.net/qy1e7to6/34/
this code works :
var msg = "";
$('table tr').each(function() {
$(this).find('td').each(function(){
msg += $(this).text() + ",";
});
msg +=" \r\n";
});
$("textarea").val(msg);
fiddler : http://jsfiddle.net/fr5htjyz/1/
you can try with
var content = '';
$('table tr').each(function(idx,elem) {
$(elem).find('tr').each(function(index,element){
content += $(element).text() + ',';
});
content.splice(0,-1);
content + = '\n';
});
$(textarea).val(content);
I asked a question yesterday and that got me going on the right path, but I'm absolutely stuck again.
Outline:
I have 3 tables;
table 1 - expected data (#expected)
table 2 - expected confirmed data (#scannedExp)
table 3 - unexpected confirmed data (#scannedUnExp)
So for a example..
if I was to enter "6666" in the input box
it would reduce qty in the "#expected" table by 1 but create a column in the "#scannedExp" table with qty of 1 (with the i.e desc, cage grabbed from the #expected table).
if we was to enter '6666' this time it would delete the "#expected" row, but increase the table "#scannedExp"
if again we was to enter '6666' this time it would add a row to "#scannedUnExp" with just the code and qty (dont need the desc or cage)
and if we was to enter say "1234" it would add a row in "#scannedUnExp"
for some reason my codes not working in Jsfiddle as it works to some extent in my browser.
http://jsfiddle.net/j3psmmo3/
<body>
<input type="text" style="width: 200px" id="code" name="code" />
<input id = "btnSubmit" type="submit" value="Submit"/>
<P>Scanned Expected</P>
<table id = "scannedExp" > <thead>
<tr>
<th>Code</th>
<th>Desc</th>
<th>Qty</th>
<th>Cage</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<P>Scanned Un Expected</P>
<table id = "scannedUnExp" > <thead>
<tr>
<th>Code</th>
<th>Qty</th>
<th>Cage</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<P>Data Expected</P>
<table id = "expected"> <thead>
<tr>
<th>Code</th>
<th>Desc</th>
<th>Qty</th>
<th>Cage</th>
</tr>
</thead>
<tbody>
<tr id="4444" >
<td>4444</td>
<th>Car Door</th>
<td>3</td>
<th>S2222</th>
</tr>
<tr id="5555" >
<td>5555</td>
<th>door handel</th>
<td>1</td>
<th>S2222</th>
</tr>
<tr id="6666" >
<td>6666</td>
<th>headlight</th>
<td>2</td>
<th>S2222</th>
</tr>
<tr id="7777">
<td>7777</td>
<th>seat</th>
<td>5</td>
<th>S2222</th>
</tr>
</tbody>
</table>
</body>
my javascript
$(window).load(function(){
$("#btnSubmit").on("click", function(){
numRows = $("#expected tr").length; //loop thought expected data
for(var i=1 ; i<numRows ; i++){
var code = $("#expected tr:nth-child(" + i + ") td:nth-child(1)").html();
var desc = $("#expected tr:nth-child(" + i + ") td:nth-child(2)").html();
var qty = $("#expected tr:nth-child(" + i + ") td:nth-child(3)").html();
var cage = $("#expected tr:nth-child(" + i + ") td:nth-child(4)").html();
// if code is in expected data -1 from qty col
if(code == $("#code").val()){
$("#expected tr:nth-child(" + i + ") td:nth-child(3)").html(parseInt(qty) - 1);
//delete if last one in expected table
if(qty ==1 ){$("#" + code).remove();}
// loop thought scanned expected table
numRowsB = $("#scannedExp tr").length;
for(var ib=1 ; ib<numRows ; ib++){
var codeExp = $("#scannedExp tr:nth-child(" + ib + ") td:nth-child(1)").html();
var qtyExp = $("#scannedExp tr:nth-child(" + ib + ") td:nth-child(3)").html();
// if in scannedExp add qty by one
if(codeExp == $("#code").val()){
$("#scannedExp tr:nth-child(" + ib + ") td:nth-child(3)").html(parseInt(qtyExp) + 1);
return true;
}
else{ //if not found in expected table add row to scannedExp
$("#scannedExp tbody").append("<tr><td>" + $("#code").val() + "</td><td>" + desc + "</td><td>1</td><td>" + cage + "</td></tr>");
return true;
}
}
return true;
}
else{
alert("not in expected");
}
}})
});
I noticed from your fiddle that the button does not trigger the click event.
Your code had 3 problems that I have fixed and then the code worked fine.
First
I think you meant to use $(document).ready() instead of $(window).load().
Since you want to listen to events, it is better to wait until all DOM elements are loaded and the document is ready before attempting to do anything else.
But since the event trigger I am about to tell you about in my second point does not depend on the document being ready or not, it is not necessary. So I removed it.
Second:
I modified the code to use $(document).on('click','selector',function(){}); instead of $(element).on('click',function(){});
//Use this event
$(document).on('click','#btnSubmit',function(){
...
...
});
//Instead of using this
$("#btnSubmit").on("click", function(){
...
...
});
the .on() I used will work for DOM controls that have been loaded from the page, or ones that you added dynamically. That's why I rely on it all the time.
Third
You forgot a semi-colon at the last line of your code...
...
...
else{
alert("not in expected");
}
}}) // <-- This line has no semi-colon
});
You may check the modified code on this fiddle
The code works fine after the modification.
using php to echo json array inline i want js/jquery to populate table according to these data.
HTML table
<table>
<thead>
<tr>
<th>Time</th>
<th data-day='2013-03-15'>15-3</th>
<th data-day='2013-03-16'>16-3</th>
<th data-day='2013-03-17'>17-3</th>
</tr>
</thead>
<tbody>
<tr data-time='09'>
<td>9am</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script>
var arr=[
{"date":"2013-03-15","id":"4","time_booked":"09:00:00"},
{"date":"2013-03-15","id":"1","time_booked":"09:10:00"},
{"date":"2013-03-17","id":"5","time_booked":"09:30:00"}
];
$.each(arr,function(){
console.log('id:'+this.id+'inside:'+this.date+'|'+this.time_booked);
});
</script>
i want to loop thro arr and according to its date and time_booked write id inside td.
for example first row will go to td with date-day='2013-03-15' and data-time='09'
so how can i do this using javascript ?
im thinking should i include data-day,data-time inside each td in tbody ? or is there a better way to do it ?
current approach:
include data-day inside each tr so html of tbody is
<tr data-time='09'>
<td data-day='2013-03-15'></td>
<td data-day='2013-03-16'></td>
etc..
</tr>
then use js
$.each(arr,function(){
var rday=this.date;
var rtime=this.time_booked;
var sel='tr[data-hr="'+rtime.substr(0,2)+'"]';
var dom=$(sel).find('td[data-day="'+rday+'"]').first();
if(dom.length)dom.append(this.id);
});
but i have a feeling its stupid ! there must be a way to map table using x,y (table head,row head) or there is none ?
I think the jQuery index function is what you're looking for. In the code sample below, I've used it to fetch the colIndex for the date. In this case, it fetches all of the th cells within the table, and uses .index(..) with a selector seeking the required date. This gives the column index of the date you're seeking, and from there it's all pretty straight-forward.
var arr=[
{"date":"2013-03-15","id":"4","time_booked":"0900"},
{"date":"2013-03-15","id":"1","time_booked":"0910"},
{"date":"2013-03-17","id":"5","time_booked":"0930"}
];
$.each(arr,function(){
var cell = GetCellByDateAndTime(this.date, this.time_booked);
$(cell).text(this.id);
});
function GetCellByDateAndTime(date, time) {
var colIndex = $("#BookingsTable th").index($("[data-day='" + date + "']"));
var row = $("#BookingsTable tr[data-time='" + time + "']")
var cell = $(row).children($("td"))[colIndex];
return cell;
}
And a Fiddle.
I have a table structure:
<table id="tableId">
<tbody id="tbodyId">
<tr id="trId1">
<td>id</td><td>name</td>
</tr>
</tbody>
</table>
I am adding new row with simple Javascript like this:
var itemsContainer = dojo.byId('tbodyId');
itemCount++; //it will give id to tr i.e. trId2
var newItemNode = document.createElement('tr');
newItemNode.setAttribute("id", 'trId' + itemCount);
newItemNode.innerHTML ='<td>id</td><td>anotherName</td>';
itemsContainer.appendChild(newItemNode);
All works fine in Firefox but row is not appended in IE. New table after it in Firefox becomes:
<table id="tableId">
<tbody id="tbodyId">
<tr id="trId1">
<td>id</td><td>name</td>
</tr>
<tr id="trId2">
<td>id</td><td>anotherName</td>
</tr>
</tbody>
</table>
I saw other codes and help. I only want one tbody in this table with simple Javascript no jQuery.
There are special functions for creating table cells ( and rows ) eg - insertRow for rows and insertCell for cells - it works in all browsers
var newItemNode = itemsContainer.insertRow( itemsContainer.rows.length - 1 );
newItemNode.setAttribute("id", 'trId' + itemCount);
var cell = newItemNode.insertCell( 0 );
cell.innerHTML = 'id';
...
PS. I think DOJO Framework have something for inserting rows and cells
First off, this jsfiddle works fine in FF6 & IE8
Make sure that your real html has the proper markup. Your example shows a closing tbody element without the slash
<tr id="trId2">
<td>id</td><td>anotherName</td>
</tr>
<tbody> <!-- This line should be </tbody> -->
IE is inconsistant with its acceptance of bad markup.
In addition, code like this:
var newItemNode = document.createElement('tr');
newItemNode.setAttribute("id", 'trId' + itemCount);
newItemNode.innerHTML ='<td>id</td><td>anotherName</td>';
Is exactly the sort of code that toolkits like dojo (and its smarter cousin, jQuery) are built to avoid. I suspect the code for creating a new row are different in the version of IE you're testing on.
try this
<html>
<script language = "javascript">
function kk()
{
var itemsContainer = document.getElementById("tbodyId");
var newItemNode = document.createElement('tr');
newItemNode.setAttribute("id", 'trId' + 1);
var newCellItem1 = document.createElement('td');
newCellItem1.innerHTML = "id";
var newCellItem2 = document.createElement('td');
newCellItem2.innerHTML = "anotherName";
newItemNode.appendChild(newCellItem1);
newItemNode.appendChild(newCellItem2);
itemsContainer.appendChild(newItemNode);
}
</script>
<table id="tableId">
<tbody id="tbodyId">
<tr id="trId1">
<td>id</td><td>name</td>
</tr>
</tbody>
</table>
<input type="button" value = "heihei" onclick = "kk();"></input>
</html>
I want reorder table rows using JavaScript .
for example take the following dummy table:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
<td>D1</td>
</tr>
</table>
I want to do this in JavaScript without using jQuery. I want to show the A1,B1,C1,D1.. row as the first row and then 1,2,3,4 row and then A,B,C,D row.
I know that there will be some wait time on the client side but I need to do it in the client side. Is there some generic solution to do this, for any number of rows?
If I understand correctly, you are asking how to take the last row and make it the first row, pushing down the rest. This should do it:
<table id="mytable">
...
</table>
<script type="text/javascript">
var tbl = document.getElementById('mytable');
var rows = tbl.getElementsByTagName('tr');
var firstRow = rows[0];
var lastRow = rows[rows.length];
firstRow.parentNode.insertBefore(lastRow.parentNode.removeChild(lastRow), firstRow);
</script>
Assuming your table does not have nested tables. At which point this would need to be a little smarter. This also assumes you're not using TBODY and THEAD nodes. But I'm sure you can get the idea and enhance it from there.
Do:
var table = ...; // Get reference to table (by ID or other means)
var lastRow = table.rows[table.rows.length - 1];
lastRow.parent.insertBefore(table.rows[0], lastRow);
The best way to solve this in Javascript is:
Give the Tr.. a unique name. for eg: X_Y,X_Z,A_Y,A_Z
Now add a hidden lable or text Box which gives the sorting order from the server i.e When the page renders I want to sort it All the Tr's that have a ID starting with A should come first and All the Z's should come second.
<asp:label id="lblFirstSortOrder" runat="server" style="display:none;">A,X</label>
<asp:label id="lblSecondSortOrder" runat="server" style="display:none;">Z,Y</label>
When the page renders..the order should be A_Z,A_Y,X_Z,X_Y
Before Rendering this is table that comes from the aspx file:
<table>
<tr id='Tr_Heading'>
<td>A</td>
<td>B</td>
</tr>
<tr id="Tr_X_Y">
<td>GH</td>
<td>GH1</td>
</tr>
<tr id="tr_X_Z">
<td>HU</td>
<td>HU1</td>
</tr>
<tr id="tr_A_Z">
<td>JI</td>
<td>JI1</td>
</tr>
<tr id="tr_A_Y">
<td>JI</td>
<td>JI1</td>
</tr>
Script:
function SortAndArrange()
{
var firstList = document.getElementById('lblFirstSortOrder').value;
var secondList = document.getElementById('lblSecondSortOrder').value;
var firstTypes = new Array();
firstTypes = firstList.split(',');
var secondLists = new Array();
secondLists = secondList.split(',');
var refNode = document.getElementById('Tbl_' + firstTypes[0] + "_" + secondTypes[0]);
for (var i = 0; i<firstTypes.length; i++)
{
for (var j = 0; j< secondTypes.length;j++)
{
var TrName = 'Tbl_'+firstTypes[i]+'_'+secondTypes[j];
var FirstSecondTrs = document.getElementById(TrName);
if (FirstSecondTrs)
{
FirstSecondTrs.parentNode.removeChild(FirstSecondTrs);
insertAfter(refNode,FirstSecondTrs);
refNode = FirstSecondTrs;
}
}
}
}
function insertAfter( referenceNode, newNode )
{
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
I hope you guys get the idea.. for me the sorting order will always come from the server and not from the user of the page...
Thanks a Lot for all the answers.. Apprecite it. Helped me get to this solution.
Thanks,
Ben