Possible to append html before and after template? - javascript

Is it possible to append html before and after a JQuery.tmpl?
I would like to insert a nested table in
<table id="accTable">
<tr class="row" id="12345">
</tr>
<!-- New row to be inserted here -->
</table>
so I have done
var dat = [];
$.each(result, function(key, value){
dat.push({
FROM: this.date,
ID: key,
});
});
var markup = "<tr> <td>${ID}</td> <td>${FROM}</td> </tr>";
$.template("actTemplate", markup);
$('#'+id).tmpl("actTemplate", dat).after('#'+id);
But somehow I need to append <tr><td><table> and prepend </table></td></tr>.
I have thought about adding that HTML to the existing, but it should happen in a button press, so until it is pressed would it look wrong. So I guess the append and prepend have to happen when the template is inserted...?
Any suggestions on how to solve this?
Update
In this jsFiffle will a row be added/removed when "Details" is clicked. This is the row that I would like to replace.
http://jsfiddle.net/littlesandra88/hhMM6/

You can make it this way:
EDITED
var wrapper = $( '<tr id="details"><td><table></table></td></tr>' );
var wrapperTable = wrapper.find( 'table' );
$.tmpl ("actTemplate", dat ).appendTo( wrapperTable );
wrapper.insertAfter( '#'+id );

I would solve it this way:
//create your wrapping elements
var wrapping_elements = $('<tr><td><table class="new-table"/></td></tr>');
$('#'+id).after(wrapping_elements);
//insert your table data
var template_data = $('#'+id).tmpl("actTemplate", dat);
$('table.new-table').append(template_data);

Related

Create row in html table which does not have id and class

I would like to create one additional row in HTML Table which is very common and can be done if we have id or class available of that table.
But in my case I have one page which contains many forms and tables.
But in all those I have one form which contains only one element i.e table and I would like to create one more row and move few columns from 1st row to newly created row.
For this I have created simple HTML page.Please find below code and help me to achieve my output.
<h:form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</h:form>
Here Ia m getting output like
Item Info Description Product Keywords Documents Image Video
But I want to achieve something like below:
Item Info Description Product Keywords
NEW CELL1 Documents Image Video
means I would like to remove few columns from existing row and I would like to add it in newly created row.
For this I have written Javascript like:
<script type="text/javascript">
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.elements[0];
var tr = document.createElement("tr");
tr.id="row2";
table.appendChild(tr);
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
var col5 = document.getElementById("col5");
tr.appendChild(col5);
var col6 = document.getElementById("col6");
tr.appendChild(col6);
var col7 = document.getElementById("col7");
tr.appendChild(col7);
}
</script>
Here, My problem is this entire form will be generated automatically so I can't give the Id for the table and with this script it is not identifying my table when I am giving form.elemets[0];
I want to find table element so that I can create row in that table.
You can find the table by doing this:
Get one of the elements in a table row, and get the parent node until you've got the table. In this case you could do document.getElementById('col1').parentNode.parentNode
And just to ease things,
You can insert this string '</tr><tr>' in a row, after a table cell, to easily create a new row.
This should be better than document.getElementsByTagName('table'), because if you have lots of tables which are far away, it will take more time to find your table's index in that array.
Use getElementsByTagName to get the table from within your form, which has an ID
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.getElementsByTagName("table")[0];
var tr = document.createElement("tr");
tr.id = "row2";
table.appendChild(tr);
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
/*Your original code produces duplicate IDs which is a BAD thing*/
var col5 = document.getElementById("col5");
/*Update new Id*/
col5.id += "_new";
tr.appendChild(col5);
var col6 = document.getElementById("col6");
/*Update new Id*/
col6.id += "_new";
tr.appendChild(col6);
var col7 = document.getElementById("col7");
/*Update new Id*/
col7.id += "_new";
tr.appendChild(col7);
}
<form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</form>
You also have a mismatch of column numbers, with the code provided you originally have 7 columns and only insert 4, this will produce inconsistent results, make sure to use the colspan attribute as needed.
You should be able to use JavaScript's querySelector method to select the table data you want to remove from the document.
Something like var rowToDeleteOrAddTo = document.querySelector("#myForm > table > tr > td"); should help you get there. You'll need to lookup CSS Selectors to get the specific selectors you need. You may need to use the textContent property once you have a node to make sure you are deleting the right one.

Finding last occurrence of text

I have the following type of table in html, which is generated dynamically by php :
<tr><td>Kiss the Girls</td><td>2016-01-01</td></tr>
<tr><td>Kiss the Girls</td><td>2016-02-05</td></tr>
<tr><td>Along Came a Spider</td><td>2016-01-07</td></tr>
<tr><td>Along Came a Spider</td><td>2016-01-22</td></tr>
<tr><td>Along Came a Spider</td><td>2016-03-31</td></tr>
I would like to be able to have a dynamic display filter that would allow the user to click a box and hide all but the latest version of the manuscript. So it might look like :
<tr><td>Kiss the Girls</td><td>2016-02-05</td></tr>
<tr><td>Along Came a Spider</td><td>2016-03-31</td></tr>
At this point none of the <tr> or <td> tags have an id or a class, but I could easily add a class to the first column (e.g., <td class='bookTitle'>). There is only one table on the page and php sorts it by date already. I'm open to jQuery or native JavaScript, though I would think this would be easier with jQuery. Seems like it could be done by just grabbing the last row before it changes names, but I'm not sure how to do that. Any thoughts?
According to 'Seems like it could be done by just grabbing the last row before it changes names', this is what I've come out with:
var rows = $("table tr");
if(rows.length > 0){
var last = $(rows[0]).find('td')[0].innerText;
for(var i=1; i<rows.length; i++){
var row = $(rows[i]);
var text = row.find('td')[0].innerText;
if(text === last){
$(rows[i-1]).hide();
}
last = text;
}
}
See the Pen Finding last occurrence of text by Tan Li Hau (#tanhauhau) on CodePen.
Iterate over the tr and store in key value pair where key as td content and value as object, after get the objects from it.
var a = {}; // object for storing dom element object
$('table tr').each(function() {
a[$('td:first', this).text().trim()] = this; // update the dom element object based on the column
});
var $res = $($.map(a, function(v) {
return v; // get objects and convert to jQuery object
}));
console.log($res);
$res.css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>Kiss the Girls</td>
<td>2016-01-01</td>
</tr>
<tr>
<td>Kiss the Girls</td>
<td>2016-02-05</td>
</tr>
<tr>
<td>Along Came a Spider</td>
<td>2016-01-07</td>
</tr>
<tr>
<td>Along Came a Spider</td>
<td>2016-01-22</td>
</tr>
<tr>
<td>Along Came a Spider</td>
<td>2016-03-31</td>
</tr>
</table>
FYI : If you want to maintain the order then the value with index and object array and set order based on that
You could iterate in reverse and remove everything you've seen before as you go:
function filterPreviousVersions ( ) {
var seen = {};
$( $('tr').get( ).reverse( ) ).each( function ( ) {
var text = $( 'td', this ).first( ).text();
if ( seen[ text ] )
$( this ).remove();
seen[ text ] = true;
} );
}
filterPreviousVersions();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>Kiss the Girls</td>
<td>2016-01-01</td>
</tr>
<tr>
<td>Kiss the Girls</td>
<td>2016-02-05</td>
</tr>
<tr>
<td>Along Came a Spider</td>
<td>2016-01-07</td>
</tr>
<tr>
<td>Along Came a Spider</td>
<td>2016-01-22</td>
</tr>
<tr>
<td>Along Came a Spider</td>
<td>2016-03-31</td>
</tr>
</table>
If you add ids in increasing order as you add the rows,
You may use this :
var valArray = [];
$('.maindiv').each(function() {
valArray.push(parseInt($(this).attr('id'), 10));
})
valArray.sort(function(a, b) {
return a - b
})
alert("Last row : " + document.getElementById(valArray[valArray.length - 1]).innerHTML); // highest`
alert("Second last : " + document.getElementById(valArray[valArray.length - 2]).innerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="2" class="maindiv">Contents in row 2</div>
<div id="5" class="maindiv">Contents in row 5</div>
<div id="3" class="maindiv">Contents in row 3</div>
<div id="1" class="maindiv">Contents in row 1</div>
<div class="main">Contents in test row</div>
<div id="4" class="maindiv">Contents in row 4</div>
To put it all together:
Succint: (May have some performance impact for large tables with many duplicate values)
$('tr').each(function(){
$("tr :contains('" + $('td', this).first().html() + "')").last()
.parent().css('color', 'red');
});
Explanation for the succint version:-
$('tr').each(function(){ // for each row of the table
$("tr // find a child inside a tr
:contains('" // that contains the text
+ $('td', this) // present within a td of the row (in line 1)
.first().html() // at the beginning
+ "')") // Using string concat to pass variable to `contains` selector)
.last() // at the end (last occurence of text)
.parent() // invoke `parent()` to select whole row
.css('color', 'red'); // apply css to identify the desired row.
});
Verbose: (Using Set of ECMAScript6 or $.unique() to remove duplicates from the full list of names. This way, when the forEach loop at the end of the code runs, it'll iterate only one per name.)
var uniqueNames = [];
$('tr').each(function(){
uniqueNames.push($('td', this).first().html());
}); // this will return the list of names from the table
// Remove duplicates from the list of names
uniqueNames = new Set(uniqueNames); // OR: uniqueNames = $.unique(uniqueNames);
uniqueNames.forEach(function(el){
$("tr :contains('" + el + "')").last().parent().css('color', 'red');
});

td's in table creating with jquery without html

Here is my jsfiddle work. I have some issues with generating table without any html. I have one json object that i need to itterate and to put keys and values in table like:
<tr> <td> key </td> <td> key </td> ... </tr>
<tr> <td> val </td> <td> val </td> ... </tr>
I tried first to generate the table like this one, but next i wanted to use jquery version of creating td's and tr's, but the all keys and values were appended in only one td and actually this is not what i want.
You have to loop through keys the first time to set the head of table, after that make the rows inside each and append every one to the table to make the body of your table, check example code bellow :
$.ajax({
type : "POST",
dataType : "json",
url : '/echo/json/',
data : { json: JSON.stringify( jsonData ) },
success : function(data){
var jsn = $(data.markers);
//First time append table head
if(!header)
{
var row = $('<tr></tr>');
for(key in jsn[0])
{
row.append('<th>'+key+'</th>');
}
table.append(row);
header = true;
}
for ( var i = 0; i < jsn.length ; i++){
var row = $('<tr></tr>');
$.each(jsn[i], function(key,val)
{
row.append('<td>'+val+'</td>');
});
table.append(row);
}
}
});
Take a look at Working fiddle.
Hope this helps.
The issue was in the scope of the col and row variables. You must reassign them in the loop, or redeclare.
Here is the updated jsfiddle. By the way there is no need to use for loop. In jQuery it is enough to use the $.each function on the object.
From here you can see how to create table structure and replace the key and val with the actual data you need.
You need to create new row object in each for iteration:
for (var mrksIndex = 0, mrksLength = jsn.length; mrksIndex <= mrksLength; ++mrksIndex) {
row = $("<tr/>");
$.each(jsn[mrksIndex], function (key, val) {
col = $("<td/>");
col.append(key);
row.append(col);
table.append(row);
});
}
Demo: https://jsfiddle.net/6dw2u8uz/15/

Get Value of HTML cells in row clicked with Javascript

I am populating a html table based on data stored in parse.com. So the table is dynamically populated, I am including editing options for the user to add, delete and edit a row. I have managed to incorporate delete and add to the table however, my problem is I need to get the data in the cells of the row on which I click the edit button...
So what I want to do is when the user clicks on the edit button I'll open a dialog with the table row in it populated with the data in the row they have clicked, in this dialog they can change data and save. I've attached a screenshot of a sample table. So if the user clicks on the edit button on the second row, I need to obtain the data in each cell to populate the dialog.
Here is what I have tried:
var par = $(this).parent().parent(); //table row
var tdUuid = par.children("td:nth-child(1)");
var tdProx = par.children("td:nth-child(2)");
var tdOffer = par.children("td:nth-child(3)");
alert(tdUuid.html()); //for testing
This comes up as undefined.
I've also tried:
var value = $(this).children().get(1).text();
I've tried to display this in an alert but the alert doesn't display so I'm assuming this is way wrong...
If anyone could help me I'd greatly appreciate it. I'm VERY new to html/javascript and I'm feeling my way around in the dark!
EDIT
Here is my html as requested:
<div id="EditDialog" title="Edit iBeacon">
<p class ="editInfo">
Please edit fields and click save
</p>
<table id ="editingTable" class ="beaconTable ">
<thead>
<tr>
<th>UUID</th>
<th>Proximity</th>
<th>Offer</th>
</tr>
</thead>
<tbody></tbody>
</table>
<button id ="saveButton" class ="btnSave">Save</button> <button id ="cancelButton" class ="btnCan">Cancel</button>
</div>
<div id= "tableContainerHolder">
<div id = "tableContainer">
<button id ="buttonAdd">Add iBeacon</button>
<table id ="iBeaconTable" class ="beaconTable " >
<thead>
<tr>
<th>UUID</th>
<th>Proximity</th>
<th>Offer</th>
<th>Editing Options</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script>
$(function() {
$("#EditDialog").dialog({
autoOpen: false
});
});
</script>
FURTHER EDIT
Here is how I populate my table:
$('#iBeaconTable').append('<tr><td id = "uuid">' + object.get('uuid') + '</td><td = "proxId">' + object.get('proximity') + '</td><td = "offerId">' + object.get('offer_content') + '</td><td><Button id = "btnEdit" onclick = "openDialog()">Edit</Button><Button id = "btnDelete" onclick = "Delete()">Delete</Button></td></tr>');
So I add the buttons each time in each row.
additional edit
Apologies for omitting code
function openDialog() {
var par = $(this).parent().parent(); //table row
var tdUuid = par.children("td:nth-child(1)");
var tdProx = par.children("td:nth-child(2)");
var tdOffer = par.children("td:nth-child(3)");
$("#EditDialog").dialog("open");
$('#editingTable').append('<tr><td id = "uuid">' +tdUuid.innerHTML+ '</td><td = "proxId">' + tdProx.html()+ '</td><td = "offerId">' + tdOffer.html());
}
The code in the openDialog() is what I had originally posted.
values in table are selected only after adding data dynamically. To get td values
var tr = $(this).closest('tr')
var tdUuid = $(tr).find('td').eq(0).text();
var tdProx = $(tr).find('td').eq(1).text();
var tdOffer = $(tr).find('td').eq(2).text();
Hope this should work.

Dynamically create div inside table using jQuery?

I am creating a div dynamically in jQuery as mentioned in the below code appending to the form.
var temp = document.createElement("div");
temp.setAttribute("id", "test");
Form:
<form id="test1" method="get">
</form>
I am trying to have a table created dynamically and need to have this inside a table?
To form table dynamically:
var tableHeader = '<table border="1"> <thead> <tr><th>QueryName</th><th>Description</th><th>Modified Date</th></tr></thead><tbody>';
$("#test").prepend(tableHeader);
Now I need to have <td> (Which I need to create) inside which I need the div element I created. Like this:
<table>
...
....
<tr>
<td>
<div id="test"> // Div i created dynamically in the top(1st line)
</div>
</td>
</tr>
How do I achieve this in jQuery?
Why don't you create the table first?
and then append the table into the dom.
give an id to the td where you want to insert your div.
$('#td-id').html({div-content-goes-here}).
the html() function puts its contents inside the selected dom node.
you can also use append(),
Try the below code:
var temp = document.createElement("div");
temp.setAttribute("id", "test");
console.log(temp);
var tableHeader = '<table border="1"> <thead> <tr><th>QueryName</th><th>Description</th><th>Modified Date</th></tr></thead><tbody>';
$('body').append(tableHeader);
$('table').append(temp);
Also check this JSFiddle and share your thoughts.
To append the div to the td of the table, you must first have such a td. The code below checks its existence and adds it if it doesn't exist.
<form id="test1" method="get"></form>
JavaScript:
var tableHeader = '<table border="1"> <thead> <tr><th>QueryName</th><th>Description</th><th>Modified Date</th></tr></thead><tbody>';
$("#test1").prepend(tableHeader);
if ($('#test1 table tr td:first-child').size()==0) {
console.log('Table has no TDs. Creating a row.');
$('#test1 table tbody').append('<tr><td></td><td></td><td></td></tr>');
}
var temp = document.createElement("div");
temp.setAttribute("id", "test");
temp.appendChild(document.createTextNode('test Div Inserted'));
// appends the DIV to the first TD of the TABLE under #test1 FORM
$('#test1 table tr td:first-child').append(temp);
JSFiddle Demo.
#user2067567, here is a healthy approach, put an id on your dynamic table, before you append it to the DOM...
var tableHeader = '<table border="1" id="mtableid"> <thead> <tr><th>QueryName</th><th>Description</th><th>Modified Date</th></tr></thead><tbody>';
...Then make your base point for manipulating your new table from this ID...
var mtable = $('#mtableid');
...Then look for the tr row you want to enter...
var firstrow = mtable.find('tr').eq(1);
...Then append content to the first row...
$('<td><div>...</div></td>').appendTo(firstrow);
This is all untested, but posted just to give you a general idea.
Let me know if you want further details.
var temp = document.createElement("div");
temp.setAttribute("id", "test");
var tableHeader = '<table border="1"> <thead> <tr><th>QueryName</th><th>Description</th><th>Modified Date</th></tr></thead><tbody>';
$("#test1").prepend(tableHeader);
$('tr').append(temp);
$('div').html('create div content');
the answer to your question is quite simple but there is an important point that you've missed to explain. Which tr do you want to append to. Do you want to create a new tr for every div you want to append to the table or is there some other logic?

Categories