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.
Related
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.
So I am having trouble deleting all of the data in an HTML table with js WITHOUT deleting the header. Here is my HTML:
<html>
<title>Z80 Opcodes</title>
<body>
<input type="text" id = "input" value = "">
<button onClick = "hex()">Hex</button>
<button onClick = "bin()">Bin</button>
<button onClick = "assem()">Assembly</button>
<button onClick = "find()">Find</button>
<table id = "out" style="width:100%">
<thead>
<th align="left">Binary</th>
<th align="left">Hex</th>
<th align="left">Assembly</th>
<th align="left">Description</th>
</thead>
<tbody id="tb">
</tbody>
<script src = "js/script.js">
</script>
</body>
</html>
And here is script.js:
var id = document.getElementById("out");
var ab = "";
var row;
var table = ['0000000000nopno operation', '0000000101ld (bc), **loads ** into BC'];
var bin = ['00000000', '00000001'];
var hex = ['00', '01'];
var assembly = ['nop', 'ld (bc), **'];
var description = ['no operation', 'loads ** into BC'];
l = table.length;
function find() {
row = id.insertRow(0);
for (i=0;i <=l-1;i++) {
ab = table[i];
if (ab.includes(document.getElementById("input").value)) {
row = id.insertRow(-1);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell1.innerHTML = bin[i];
cell2.innerHTML = hex[i];
cell3.innerHTML = assembly[i];
cell4.innerHTML = description[i];
}
}
}
I have omitted A LOT of array entries because they contained almost the FULL instruction set of thee z80 microprocessor.
What this code does (basically) is it gets an input from the user and if the array table contains that input then it gets the corresponding values from bin, hex, assembly and description and assigns each a column in the table out, then adds a row with the for the data. However, I cannot seem to find a way to delete all of the rows in tbody before another set of values are appended to the table without deleting thead. I have searched around on the web and found several solutions, none of which worked. They either deleted the thead or caused some kind of error (I'll give examples if you ask). I am using Google Chrome version 63.0.3239.132 web browser to run my code.
As you may be able to see I am quite new to js and HTML
Any ideas what I have done wrong?
~Jachdich
First You have to close your <table> tag </table>
This is how you can clear your table.
$('#remove').on('click', ()=>{
$('#tb').empty()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id = "out" style="width:100%">
<thead>
<th align="left">Binary</th>
<th align="left">Hex</th>
<th align="left">Assembly</th>
<th align="left">Description</th>
</thead>
<tbody id="tb">
<tr>
<th>01010101</th>
<th>1231:sdf:sdf42</th>
<th>213123</th>
<th>description</th>
</tr>
</tbody>
</table>
<button id="remove">
clear
</button>
Assuming you want to keep the tbody element intact instead of just removing it and all its children at once:
// get a reference to the tbody element
var tb = document.querySelector('#out tbody');
// while tb has children, remove the first one
while (tb.childNodes.length) {
tb.removeChild(tb.childNodes[0]);
}
// tb is now empty
From a semantic perspective, it would make the removal of rows much easier if you added them to the <tbody> element instead of the <thead> element. This way, you could target the rows within the body and remove them whilst preserving your <thead> (sibling node to ):
var body = document.querySelector('tbody');
while (body.firstChild) {
// This will remove all children within tbody which in your case are <tr> elements
body.removeChild(body.firstChild);
}
body.removeChild(rowsWithinBody)
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody#examples
with jQuery you can do it simply in a single line of code.
$("#table_id tbody tr").remove();
it will remove all rows in a table except the header.
I have a table, that is dynamicallly increased with Firebase, and I need a delete and edit button on each row of the table, currently, the remove button is working, but I am having trouble with the edit button, I saw a few examples around, but i'm not sure how to do it using append()...
Here's what I have so far:
HTML
<table id="tableAssets" class="mdl-data-table mdl-js-data-table mdl-shadow--2dp">
<thead>
<tr id="tableHeader">
<th class="mdl-data-table__cell--non-numeric">Name</th>
<th class="mdl-data-table__cell--non-numeric">Brand</th>
<th class="mdl-data-table__cell--non-numeric"> </th>
</tr>
</thead>
<tbody id="table_body"> </tbody>
</table>
JavaScript
rootRef.on("child_added", snap => {
var assetKey = snap.child("id").val();
var name = snap.child("name").val();
var brand = snap.child("brand").val();
$("#table_body").append("<tr data-id='"+assetKey+"'>"+
"<td class='mdl-data-table__cell--non-numeric'>" + name + "</td>" +
"<td class='mdl-data-table__cell--non-numeric'>" + brand + "</td>" +
"<td class='mdl-data-table__cell--non-numeric'><div buttons>"+
"<button class='edit-btn'><i class='material-icons'>mode_edit</i></button>"+" "+
"<button class='delete-btn'><i class='material-icons'>delete</i></button>"+" "+
"</div></td></tr>");
});
And here is what I was thinking on doing with the edit button: Hide the whole row, and add a new one with the saved information, but with text fields, and change the edit button with a save button, but I have no idea how I should be doing this...
$("#table_body").on('click','.edit-btn', function(e){
var $row = $(this).closest('tr');
$row.hide();
});
I'd suggest you to do this:
Have two rows, one for view and one for edit mode. This is easier to
maintain.
Assign an id to the whole row:
$("#table_body").append("<tr id='"+assetKey+"'>
Then when clicking that edit button, pass the id to some method as when you append you have it, it is easier. You can use something
like onclick and call the method:
<button class='edit-btn' onclick=edit(\'"+assetKey+"\')><i class='material-icons'>mode_edit</i></button>
On edit, hide the clicked button row and show the edit mode for that row. As it is already rendered, it works great if you have
multiple rows, stays in place:
('#'+id).hide();
The edit mode row "view" would show the save button or anything else you need. Use the same Technique/strategy to call a save() method.
When save is successful, rebuild both rows and replace them so everything is neat and stays in line.
And to make sense of this and it is not just in words, a functional example using your code on jsfiddle here.
Hope this is of help!
I am creating a table using Google Firebase in JavaScript, but its not showing the table.
Here is my code:
User Table <!--function called on click on tab link-->
<table id="userTableInside" class="w3-table w3-centered w3-striped w3-card-2">
<tr style="background: #cccccc;">
<th>Institute Name</th>
<th>Role id</th>
<th>Institute id</th>
<th>Strikes</th>
<th>Status</th>
<!--<th>Perfomance Rating</th>-->
</tr>
<tr id="mytr">
</tr>
</table>
Added the src script tag above
<script>
//initialized firebase also
function tab1() {
var table= document.getElementById("userTableInside");
var i = 1;
var institudeId = sessionStorage.getItem("InstituteId");
var roleId = sessionStorage.getItem("RoleId");
var ref_1 = firebase.database.ref(institudeId + "/Admin/Usertable/");
ref_1.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var row= table.insertRows(i);
var x= row.insertCell(0);
var x1= row.insertCell(1);
var x2= row.insertCell(2);
x.innerHTML = childData.status;
x1.innerHTML = childData.totalTimeUsed;
x2.innerHTML = childData.report;
i++;
// ...
});
});
</script>
Everything seems fine to me, except the snapshot.forEach. Before using the values in the snapshot, First extract the values from the snapshot using snapshot.val().
Use snapshot.val().forEach. Hope this will solve your problem.
Note:
The listener receives a snapshot that contains the data at the specified location in the database at the time of the event. You can retrieve the data in the snapshot with the val() method.
I didn't check the table insertion logic as i found that snapshot is used directly.
You need to append the data to the table
$("#userTableInside > tbody").append("" + data for col 1 + "" + data for col 2 + "" + data for col 3 + "");
use the proper variable instead of "data for col 1" etc.
make sure you end with a to indicate the end of the table row.
Do this for each time you loop thru your "children" - basically just replace your code in the same place
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);