Container element inside of a table that holds rows - javascript

I am dynamically inserting a table row (or multiple rows) into a table upon an ajax call's return. I am looking to accomplish this by having an empty container type element inside of my html table that I can insert <tr> elements into. As I have seen from other posts, a div cannot hold a tr element, so my question is, is there a particular way that I can insert the html for row(s) into a table? It must be dynamic in nature, or in other words I need to be able to hold more than just one <tr>.

You can append to last row of table.
<table>
<tr><td>First Row</td></tr>
<tr><td>Middle Row</td></tr>
<tr><td>Last Row</td></tr>
</table>
<script>
$( "#tableid tr:last" ).append(
</script>

Assuming you aren't using jQuery, you can do something like this:
var myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var row = myTable.insertRow(myTable.rows.length);
You can then insert cells using insertCell on row.
Alternatively, if you have jQuery,
$("#myTable").append("<tr><td>Table Row with cell!</td></tr>");

I'm not sure why you wouldn't just use the <table> element directly, but you can use <tbody> elements as row containers within a table.
onload = function(){
document.getElementById("aButton").onclick = addRow.bind(null, "a");
document.getElementById("bButton").onclick = addRow.bind(null, "b");
}
function addRow(id) {
var r = document.getElementById(id).insertRow(-1);
var c = r.insertCell(-1);
c.innerHTML = "Row added at " + new Date().toLocaleTimeString();
}
body {
font-family: sans-serif;
font-size: 12px;
}
table {
border-collapse: collapse;
margin: 8px 0;
}
td {
border: 1px solid #ccc;
padding: 1px 2px;
}
<button id="aButton">Add row to 'A'</button>
<button id="bButton">Add row to 'B'</button>
<table>
<tbody><tr><td>Before A</td></tr></tbody>
<tbody id="a"></tbody>
<tbody>
<tr><td>After A</td></tr>
<tr><td>Before B</td></tr>
</tbody>
<tbody id="b"></tbody>
<tbody><tr><td>After B</td></tr></tbody>
</table>

Related

How to fetch contents of clicked cell in a dynamic table using javascript

I have tables present. Now if I click any of the below table names, like feedback, how can I get the values for them. table is dynamic. Below is code for displaying table names.
<table class="table table-hover" style="margin-top: 25px;width:300px;">
<thead>
{% for i in tables %}
<tr>
<th > {{ i }} </th>
</tr>
{% endfor %}
</thead>
</table>
Note, i is value of table name.
Here I want to add 2 things:
A click listener
Get the values by clicking on the tables using JavaScript
To get the element clicked, you can listen for click events on the table, then use the event.target property to get the element that was clicked.
// set up the 'click' event listener
myTable.addEventListener('click', event => {
const clickedElement = event.target;
// now that you have the clicked element, do what you want with it
let stuffIWant = clickedElement.<some method or property of element>;
});
From the example in the question, it appears that you looking for the contents of a <th> element. If that's the case, you can use:
stuffIWant = clickedElement.innerText;
A working example:
// listen for all 'click' events within table
const tbl = document.getElementById('tbl');
tbl.addEventListener('click', event => {
const el = event.target;
alert(`you clicked "${el.innerText}"`);
});
#tbl {
background-color: #aaa;
margin: 12px;
}
th {
padding: 0.5rem 2rem;
border: 1px solid #999;
}
/* change cursor to hand on hover */
th:hover {
cursor: pointer;
}
<table id="tbl">
<thead>
<tr><th>Feedback</th></tr>
<tr><th>Complaint</th></tr>
<tr><th>Praise</th></tr>
</thead>
</table>

Add rows in HTML table with JavaScript

I'd like to write <td> tags with JavaSctipt in my HTML code.
I'm building a <table> in the main code and I'd like to continue it with a <script>, adding rows in the division.
<body>
<table>
<tr>
<td>First</td>
</tr>
<div id="searchOutput"></div>
<tr>
<td>Last</td>
</tr>
</table>
<script>
document.getElementById("searchOutput").innerHTML = "<tr><td>Middle<td><tr>";
</script>
</body>
The problem is that the <script> creates another table in a strange way.
Is there a way to add rows without writing all code (including <table> tags) in the <script>?
For insert new row in the table, you can use Table insertRow() and insertCell() Methods. The insertRow() methods creates an empty <tr> element and adds it to a table. The insertCell() method inserts a cell into the current row.
See the code below:
function addRows() {
var table = document.getElementById( 'myTable' ),
row = table.insertRow(0),
cell1 = row.insertCell(0),
cell2 = row.insertCell(1);
cell1.innerHTML = 'Cell 1';
cell2.innerHTML = 'Cell 2';
}
table {
border: 1px solid #999;
border-collapse: collapse;
width: 100%
}
td {
border: 1px solid #999
}
<p>
<button onclick="addRows()">Add a new row</button>
</p>
<table id="myTable"></table>
CertainPerformance is correct; divs should not be direct children of tables. You might find this question useful. You have the right idea, if only you could actually replace the HTML of the div as opposed to simply filling it in. So, you could set the ID of the Last tr to searchOutput. Then, something like
var newRow = document.createElement("tr");
var oldRow = document.getElementById("searchOutput");
newRow.innerHTML = "<tr><td>Middle</td></tr>";
document.getElementByTagName("table").insertBefore(row, oldRow);
Take a look at the example from w3cschools.com https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_table_insertrow

How can I make my second selection working in JavaScript?

I am using the selection. I am selecting a value and getting the result in an input box, but the problem is, it is only working in the first row of my selection and not working when I am clicking second selection. Here is the code, Please share if you can solve this one or advice.
<script type="text/javascript">
function displayResult()
{
document.getElementById("mycall1").insertRow(-1).innerHTML = '<td><select id = "forcx" onchange="fillgap()"><option>Select</option> <option>Force</option><option>Angle</option><option>Area</option></select></td>';
document.getElementById("mycall2").insertRow(-1).innerHTML = '<td><input type="text" id="result1" size = "10" ></td>';
}
function fillgap(event){
var xnumb = 20;
var forcxlist = document.getElementById("forcx");
var forcxlistValue = forcxlist.options[forcxlist.selectedIndex].text;
if (forcxlistValue == "Force"){
document.getElementById("result1").value = xnumb;
}
}
</script>
Ok, so if i understand correctly
1) You want to add the: selection, results & + to the existing table
2) Add the options Force, Angle & Area to the select
3) If Force is selected, put the value '20' in the results td
4) When the + is clicked, a new row is added.
5 The newly added rows should behave exactly the same.
Given the above, I have done the following, I'm using jQuery as its simpler and I'm more familiar with it. Its easy.
The trick here is event delegation. at the time your page loads the new rows don't exist, that's why your JavaScript isn't working on them. you can read about it here: https://learn.jquery.com/events/event-delegation/
Here's the result:
$(document).ready(function() {
// add headers to table
$('table tr:first-child').append('<th>Result</th><th>Add</th>');
//add fields to table
$('table tr:not(:first-child)').append('<td><select class="selection"><option></option><option value="Force">Force</option><option value="Angle">Angle</option><option value="Area">Area</option></select></td><td class="result"></td><td><button type="button" class="displayResultBtn">+</button></td>');
// add new row when button is clicked
$('table').on('click','.displayResultBtn', function( event) {
var tRow = $(this).parent().parent().clone();
$(this).parents('table').append(tRow);
$('table tr:last-child td.result').empty();
});
// when the dropdown is changed, update the result to 20 if "Force" is selected.
$('table').on('change','.selection', function( event) {
var selection = $(this).val();
if (selection == "Force") {
$(this).parent().next().html('20');
// You can add more coditionals if you want to add didferent values for the other options.
} else {
$(this).parent().next().empty();
}
});
});
table,
td,
th {
border: 1px solid black;
white-space: nowrap;
}
table {
border-collapse: collapse;
width: 30%;
table-layout: auto;
}
td {
text-align: center;
vertical-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table>
<tr>
<th>To</th>
<th>From</th>
<th>Detail</th>
<th>Selection</th>
</tr>
<tr>
<td>A</td>
<td>B</td>
<td>A+B</td>
</tr>
</table>
It's hard to answer with limited code provided, but I think your issue is that you are using id multiple times. Which is invalid. id should be unique and used once only.
I have put together some demo code here that will hopefully help you. It doesn't solve your exact problem(I dont have your html so i cant fully solve it). but hopefully this will give you an idea of how to handle accessing different rows, or specific unique ids.
I'm using jQuery here for simplicity, but the principle is the same:
Here's a fiddle if thats easier to play with: https://jsfiddle.net/BradChelly/4179e26q/
I hope this helps somewhat.
// highlight row by child selectors (:last-child)
$('#selectLastRowBtn').click(function(){
//clear any previous highlighting
$('#myTable tr:not(:first-child)').css('background-color','white');
// highlight the last row in the table.
$('#myTable tr:last-child').css('background-color','lightgrey');
});
// highlight row using a specific unique id
$('#selectRowByIdBtn').click(function(){
//get selected row id from dropdown
var rowId = $('#rowSelector option:selected').val();
//clear any previous highlighting
$('#myTable tr:not(:first-child)').css('background-color','white');
//highlight the row with the matching id from the selection dropdown
$('#myTable #row_'+rowId).css('background-color','lightgrey');
});
//
// ------Below is just stuff to make demo work, not relevant to the question
//
// Add row with unique id
$('#addNewRowBtn').click(function(){
var rowCount = $('#myTable tr').length;
$('#myTable').append('<tr id="row_'+rowCount+'"><td>23124</td><td>23124</td><td>23124</td><td>23124</td></tr>');
populateSelect(rowCount);
});
// populate select options
function populateSelect(rowCount){
$('#rowSelector').append('<option value="'+rowCount+'">'+rowCount+'</option>')
}
table {
width: 100%;
text-align: center;
}
table td {
border: 1px solid #333;
padding: 30px 0px;
}
table tr:first-child {
top: 0px;
background: #333;
}
table tr:first-child th {
color: #fff;
padding: 20px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<th>Column One</th>
<th>Column Two</th>
<th>Column Three</th>
<th>Column Four</th>
</tr>
<tr id="row_1">
<td>23124</td>
<td>23124</td>
<td>23124</td>
<td>23124</td>
</tr>
</table>
<button id="addNewRowBtn">Add Row</button>
<h3>Using child selectors:</h3>
<button id="selectLastRowBtn">Highlight last row using child selector</button>
<h3>Highlight a row by id:</h3>
<select name="" id="rowSelector">
<option value="1">1</option>
</select>
<button id="selectRowByIdBtn">Highlight row by selected id</button>

Jquery Append Table

html file
<div id='tweetPost'>
<table id="example">
<thead>
<tr>
<th>No</th>
<th>FistName</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
JavaScript
$("#tweetPost").append(<tr>);
$("#tweetPost").append("<td>"+tweets.statuses[i].text + "<td/>");
$("#tweetPost").append("<td>"+tweets.statuses[i].created_at +"</td>");
$("#tweetPost").append(</tr>);
Above code when i try to run it , the table wont come out.
Question : How can i append the td row inside tbody??
You should try targeting your table id example and the tbody like so:
$("#example tbody").append("<tr><td>text</td><td>created</td></tr>");
See this link for a working example: append to example table
$('#tweetPost').append('<table></table>');
var table = $('#tweetPost').children();
table.append("<tr><td>a</td><td>b</td></tr>");
table.append("<tr><td>c</td><td>d</td></tr>");
table {
background: #CCC;
border: 1px solid #000;
}
table td {
padding: 15px;
border: 1px solid #DDD;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='tweetPost'></div>
Note:- You can tackle your table id & the tbody
You are appending the tr in div instead of tbody and the is also some syntax error. Try like following.
$("#example tbody").append("<tr><td>" + tweets.statuses[i].text + "<td/><td>" + tweets.statuses[i].created_at + "</td><tr>");
You've missed inverted comma " " in first and last lines. Try this:
$("#tweetPost").append("<tr>");
$("#tweetPost").append("<td>"+tweets.statuses[i].text + "<td/>");
$("#tweetPost").append("<td>"+tweets.statuses[i].created_at +"</td>");
$("#tweetPost").append("</tr>");

refresh div on adding rows using javascript

My table is being populated using ajax from a mysql database. I have a text field below it which adds the entered data to the database. All this works fine, but what i want to do is on adding that new row to the table, i want to dynamically show the user that their entry has been added (or simply refresh that div when new field has been added). Currently aim able to achieve that using a simple function:
function addItem(new_item, edit_table) {
var itemName = new_item;
var newRow = document.createElement('tr');
var rowCell = document.createElement('td');
rowCell.textContent = itemName;
// rowCell.addClass("grid");
newRow.appendChild(rowCell);
edit_table.appendChild(newRow);
}
However this does not let me add extra functionalities to that row e.g. i have a delete and edit icon upon hover. So by using this function i am able to show the new row added but its not exactly functioning. So i recon the better option would be to refresh that div when this happens.
I am using the following code to call the addItems method:
$('#b_go').click(function(){
//some other conditions, then using ajax to post the data
success: function (data) {
if(data == 'success') {
addItem(new_row, selected_table);
}
HTML for the table:
<table class="table table-striped table-bordered home" id="subjects">
<thead>
<th>Subject Title</th>
</thead>
<tbody>
<?php
$sql = mysql_query("select Title from Subject");
while($row = mysql_fetch_array($sql)) {
echo "<tr><td>";
echo $row['Title']?> <!--using html to output buttons for delete and edit for each row-->
<?;echo "</td></tr>";
}
?>
</tbody>
</table>
Css for the above table:
.table {
width: 100%;
margin-bottom: 18px;
}
.table th, .table td {
padding: 8px;
line-height: 18px;
text-align: left;
border-top: 1px solid #ddd;
}
.table th {
font-weight: bold;
vertical-align: bottom;
}
.table td {
vertical-align: top;
}
.table thead:first-child tr th, .table thead:first-child tr td {
border-top: 0;
}
.table-striped tbody tr:nth-child(odd) td, .table-striped tbody tr:nth-child(odd) th {
background-color: #f9f9f9;
}
.home {
width: 100%;
border-collapse: collapse;
text-align: left;
}
.home th {
font-size: 15px;
font-weight: 400;
color: #039;
padding: 10px 8px;
border-bottom: 2px solid #6678b1;
}
.home td {
line-height:15px;
border-bottom: 1px solid #E0E0E0;
border-left: 1px solid #E0E0E0;
font-size: 12px;
color: #404040;
padding: 9px 8px 3px 8px;
}
.home tbody tr:hover td {
background-color:#E6E6FF;
cursor: pointer;
}
Any help would be appreciated!
I have to leave work, but here's a quick and dirty answer.
When adding new elements dynamically that have pre-existing functions/events/actions that are already bound, the new elements will not automatically inherent the events/actions of their siblings. I recommend using jQuery for something like this.
For jQuery versions greater than 1.3 - use jQuery LIVE() function:
http://api.jquery.com/live/
Description: This will map the data passed to your new event handlers needed
For jQuery versions 1.7 or higher - use jquery ON() function:
http://api.jquery.com/on/
Description: method attaches event handlers to the currently selected set of elements in the jQuery object. This will attach the event handler to any new element you create.
Update: 11:57 AM Tuesday: Based on your comment. You need to use bind('click') or on('') function when you SUBMIT the form.
// First : Change your click code to this. You'll need the bind() function here. This will make it so your events will bind to each new row
$('#b_go').bind("click", function(){
//some other conditions, then using ajax to post the data
success: function (data) {
if(data == 'success') {
addItem(new_row, selected_table);
}
// Change your function to this:
function addItem(new_item, edit_table) {
var itemName = new_item;
var newRow = document.createElement('tr');
var rowCell = document.createElement('td');
rowCell.textContent = itemName;
$(rowCell).addClass("grid"); // Make sure GRID is the class being applied to your other TDs/TRs etc
newRow.appendChild(rowCell);
edit_table.appendChild(newRow);
$(edit_table +' tr:odd td').css('background','#f9f9f9'); // Set color for all odd rows.
}
HOW TO RELOAD TABLE:
STEP #1 - Create a new < div > layer with an ID #getDataGrid. THIS MUST WRAP AROUND YOUR TABLE.
STEP #2 - Create a new file like : data-grid.php and include the following HTML. Please also include any PHP business logic that would be needed to make the appropriate database calls to make this code successful:
<table class="table table-striped table-bordered home" id="subjects">
<thead>
<th>Subject Title</th>
</thead>
<tbody>
<?php
$sql = mysql_query("select Title from Subject");
while($row = mysql_fetch_array($sql)) {
echo "<tr><td>";
echo $row['Title']?> <!--using html to output buttons for delete and edit for each row-->
<?;echo "</td></tr>";
}
?>
</tbody>
</table>
STEP #3 : Update your click function:
$('#b_go').bind("click", function(){
//some other conditions, then using ajax to post the data
success: function (data) {
if(data == 'success') {
addItem(new_row, selected_table);
$.get('data-grid.php', function(getTable) {
$('#getDataGrid').html(getTable);
});
}
EXPLANATION. What this is doing on your click function is using jQuery to essentially perform a "GET" (just as PHP GET would perform). We are retrieveing our newly created data-grid.php file, and then PLACING the contents into the #getDataGrid div layer we created that wraps around the table. What this will do will actually wipe out the currently displayed table with the new displayed table.
Instead of only partially using a DOM approach, create the TD in javascript too.
function addItem(itemName) {
var newRow = document.createElement('tr');
var rowCell = documentcreateElement('td');
rowCell.textContent = itemName;
newRow.appendChild(rowCell);
document.getElementById('subjects').appendChild(newRow);
}
Do you have JQuery? You can make something similar in JS, but here's the concept.
Create a template of the new row in HTML
Add the row to the DB.
Add the row to the table:
var row = $("#myRowTemplate").clone();
row.attr("id", "");
//Bind the new data
row.find(".fname").text("Jack");
row.find(".lname").text("Dean");
//Bind a click event on the first name
row.find(".fname").click(function(){alert('Hi!');});
$("#myTable").find("tbody :first").append(row);
Hopes that's helps :)

Categories

Resources