Adding a row and sorting table using JavaScript - javascript

I am running into a very small issue which has taken more than two hours.
What I want is to insert a row in an HTML table and then sort it in ascending order. I've looked at this answer and thought that I can get this simple task working, but in vein.
Here is my little form and table:
Name: <input type="text" name="name" id="name"><br>
Status: <input type="text" name="status" id="status">><br>
<button onclick="myFunction(document.getElementsByName('name')[0].value,document.getElementsByName('status')[0].value)">Click</button><br><br>
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Doe, John</td>
<td>Approved</td>
</tr>
<tr>
<td>aaa, John</td>
<td>Approved</td>
</tr>
</tbody>
</table>
My inline JavaScript function looks like this:
function myFunction(name, status) {
var table = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = name;
cell2.innerHTML = status;
// The following code should sort the table.
var tbody = $('#mytable').find('tbody');
tbody.find('tr').sort(function (a, b) {
return $('td:first', a).text().localeCompare($('td:first', b).text());
}).appendTo(tbody);
}
Please note that adding a row to the table works fine, it just adds it to the top.
There are no console errors. The code which (apparently) should sort the table does not do anything. I've the subset of my HTML here on Fiddle, and yes that works fine.
I know about jQuery tablesorter plugin but do not need to use it.

This selector:
$('#mytable')
...is incorrect. Your table's ID is myTable, and IDs are case-sensitive. Here's a working version of your code with that fix.

Related

Populate a form text area on table row selection - Python Flask HTML

Need help with populating a text area based on html table row selection.
In the table below, I want to extract the content of the column 'Comments' for the selected row and write into the text area 'Comment' on the same page. I have only managed to create the table but nothing else.
Below is the code I have now created from this link. What is happening now is that only the currently selected cell gets put in the text box instead of just the 'Comment' column. I want to input only in the 'Comment' column into the box regardless of the cell clicked upon in the row.
<table id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Comments</th>
</tr>
<tbody>
<tr>
<td>John</td>
<td>42</td>
<td>avery long comment</td>
</tr>
<tr>
<td>Peter</td>
<td>35</td>
<td>another very long comment</td>
</tr>
<tr>
<td>Mary</td>
<td>54</td>
<td>some comment</td>
</tr>
</tbody>
</table>
<script>
var table = document.getElementById('table');
var selected = table.getElementsByClassName('selected');
table.onclick = highlight;
function highlight(e) {
if (selected[0]) selected[0].className = '';
e.target.parentNode.className = 'selected';
var element = document.querySelectorAll('.selected');
if (element[0] !== undefined) { //it must be selected
document.getElementById("myTextbox").value = element[0].children[0].firstChild.data
}
}
</script>
<div >
<textarea class="form-control" id="myTextbox"></textarea>
</div>
Thanks for your help.
You're getting the first column but you can get the third column with the comment by changing the index of the child to 2 instead of 0.
document.getElementById("myTextbox").value = element[0].children[2].firstChild.data

Javascript: extract cell data from table

I have a scenario where there is a table of 4 rows, in the 4th row is a textbox. When an "onchange" event of the textbox is triggered, I want to extract the data in the cells of the same specific row into another table. and ofcourse my table is consisted of more than one row.
<div class="ProductsTable">
<table class="tablestyle">
<tr>
<th>Item</th>
<th>Price</th>
<th>Preview</th>
<th class="auto-style4">Quantity</th>
<th class="auto-style15">Selected Items</th>
</tr>
<tr id="row1">
<td class="auto-style1" id="item_name">Sofa</td>
<td class="auto-style2" id="item_price">$280.00</td>
<td class="auto-style3">
<img class="itemimage" src="images\sofa1.jpg" />
</td>
<td class="auto-style4">
<input class="quantitybox" id="item_quantity" type="text" onchange="get_quantity();" />
</td>
<td rowspan="10">
<table class="InvoiceTable" id="invoice">
<tr>
<th class="auto-style7">Item</th>
<th class="auto-style2">Price</th>
<th class="auto-style4">Quantity</th>
</tr>
</table>
</td>
</tr>
</table>
</div>
And my javascript is:
function get_quantity() {
var table = document.getElementById("invoice");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2)
cell1.innerHTML = document.getElementById("item_name").innerHTML;
cell2.innerHTML = document.getElementById("item_price").innerHTML;
cell3.innerHTML = document.getElementById("item_quantity").value;
}
How can I create a loop to check through all my table when an "onchange" event is triggered. As I actually have 10 rows in my table.
Preferably without using jquery.
If I understand you correctly you are looking for a function to copy the content of the changed row, that is the data in each column, into the invoice table.
I expect the rows to be created dynamicaly with some sort of iteration. When iterating I expect a unique number is availabe why this can be used as a general selector.
Here is a function to do this:
function get_quantity(rowNumber) {
var table = document.getElementById("invoice" + rowNumber);
var row = table.insertRow(1);
var columns = document.getElementById("row" + rowNumber).childNodes;
var dataColumnIndex = 0;
for (var i = 0; i < columns.length; i++) {
if (columns[i].className == "data") {
var cell = row.insertCell(dataColumnIndex);
cell.innerHTML = columns[i].innerHTML;
dataColumnIndex++;
}
}
var inputQuantity = document.getElementById("item_quantity" + rowNumber).value
row.insertCell(dataColumnIndex).innerHTML = inputQuantity;
}
You select what columns to copy by marking the them with class data.
I gets the invoice table by expecting it to have the id invoice + number. Fx. invoice1. Same goes with each row and the input field.
Here is a plunker with a full example.
Edit
There should only be a single invoice table where all products are added to.
By selecting the same table for row insertion in the function this is fixed.
This updated plunker has the change

Why can't I make a Table row using JavaScript and a <div>?

For some reason the following piece of code does not work to insert an extra table into my html document. The text is just randomly sitting at the top of the table instead of IN the table. Any ideas why it doesn't work?
<!DOCTYPE html>
<head>
<script type = "text/javascript">
function insertTable() {
var table = document.getElementById("houseListingTable").innerHTML;
table = table + "<tr><td>58,500</td><td>Montreal</td></tr>";
}
</script>
</head>
<body>
<table>
<tr>
<th>Price</th>
<th>Location</th>
</tr>
<div id = "houseListingTable">
</div>
</table>
<button onclick = "insertTable()">Insert Table<\button>
</body>
</html>
Why doesn't the table row add itself to my table when I click on the Insert Table button? Any help is appreciated!!
There are two problems here:
Having a <div> element directly inside a <table> is invalid HTML.
Your table variable here is just a string. Overwriting it has no effect on the DOM.
To fix it:
Remove the <div> and give the <table> an ID:
<table id="houseListingTable">
<tr>
<th>Price<\th>
<th>Location<\th>
</tr>
</table>
Use this JavaScript:
var table = document.getElementById("houseListingTable");
table.innerHTML += "<tr><td>58,500</td><td>Montreal</td></tr>";
Note how I am actually overwriting the table's .innerHTML property. This is an important distinction from what you have there.
Just a couple of comments before the answer. Please note that you are missing the html tag at the begging, and that you are using the incorrect bar "\" to close tags in table headers (it should be < /th>) and in the button tag (< /button>).
Also, the div inside the table is not correct.
The code does nothing because the function just gets the innerHTML. For your purpose, the function should get what's inside the table, add a row and then paste it back on the table
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function insertTable() {
var table = document.getElementById("houseListingTable").innerHTML;
table = table + "<tr><td>58,500</td><td>Montreal</td></tr>";
document.getElementById("houseListingTable").innerHTML = table;
}
</script>
</head>
<body>
<table id="houseListingTable">
<tr>
<th>Price</th>
<th>Location</th>
</tr>
</table>
<button onclick = "insertTable()">Insert Table</button>
</body>
</html>
Your HTML is broken. The ending tags are wrong.
<table id="houseListingTable">
<tr>
<th>Price</th>
<th>Location</th>
</tr>
</table>
You can use the insertRow of DOM method to add rows to table by getting the table first by Id
function insertTable() {
// Find a <table> element with id="houseListingTable":
var table = document.getElementById("houseListingTable");
// Create an empty <tr> element and add it to the table:
var row = table.insertRow(table.rows.length);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Append a text node to the cell1
var price = document.createTextNode('58,500')
cell1.appendChild(price);
// Append a text node to the cell2
var location = document.createTextNode('Montreal')
cell2.appendChild(location);
}

Problems with traversing table using DOM

I managed to fix some trouble I was having with traversing through table rows with DOM using only JavaScript but ran into 2 hurdles. I'm trying to create a table, where each row will have a set of buttons to move that particular row up, down or remove it. I was able to successfully use the .replaceChild method but it replaces the row instead of just swapping them. When I tried .moveRow, I keep getting an error saying the HTML table section does not have that method. I run into the same problem when trying to swap the current row with the row below. Any suggestions?
function up(x){
// var tableBody = document.getElementsByTagName("tbody")[0]; // tried it with tableBody and it still didn't work
var table = x.parentNode.parentNode.parentNode;
var tableRow = x.parentNode.parentNode.cloneNode(true);
var previousRow = x.parentNode.parentNode.previousSibling.cloneNode(true);
table.replaceChild(tableRow,x.parentNode.parentNode.previousSibling);
}
function down(x){
var table = x.parentNode.parentNode.parentNode;
var tableRow = x.parentNote.parentNode.cloneNode(true);
var belowRow = x.parentNode.parentNode.nextSibling.cloneNode(true);
table.moveRow(tableRow,x.parentNode.parentNode.nextSibling);
}
My buttons:
<table id="table1" border="1">
<tbody>
<tr>
<th>Column 1</th> <th>Column 2</th> <th>Column 3</th> <th>Column 4</th>
</tr>
<tr id="enterData">
<td id="buttons">
<input type="button" value="Up" onclick="up(this)" />
<input type="button" value="Down" onclick="down(this)" />
</td>
</tr>
</tbody>
</table>
You can use insertBefore to move up or down the rows and appendChild for the last row, also I use *ElementSibling to avoid text node issues but that might cause compatibily issues.
function up(x){
var row = x.parentNode.parentNode;
var table = row.parentNode;
//Don't move up over the header
if (row.previousElementSibling && row.previousElementSibling.previousElementSibling){
table.insertBefore(row,row.previousElementSibling);
}
}
function down(x){
var row = x.parentNode.parentNode;
var table = row.parentNode;
//can't use insertBefore for last row.
if (row.nextElementSibling && row.nextElementSibling.nextElementSibling){
table.insertBefore(row,row.nextElementSibling.nextElementSibling);
}
else{
table.appendChild(row);
}
}
DEMO

How to get row id from row Index in table using JavaScript

Suppose this is my table:
<table>
<tr id="a">
<TD>a</TD>
</tr>
<tr id="b">
<TD>b</TD>
</tr>
</table>
How can I get row id using the row index from a table?
Above is just an example where id is static but in my case my id is dynamic, so I can't use
document.getElementById().
Assuming you have only one table on your page:
document.getElementsByTagName("tr")[index].id;
Preferably though, you'd give your table a id, though, and get your row like this:
<table id="tableId">
<tr id="a">
<td>a</td>
</tr>
<tr id="b">
<td>b</td>
</tr>
</table>
var table = document.getElementById("tableId");
var row = table.rows[index];
console.log(row.id);
This way, you can be certain you don't get any interference, if you have multiple tables in your page.
"So, How can i get row id using row Index from a table"
You would select the table, and use the .rows property to get the row by index.
var table = document.getElementsByTagName("table")[0]; // first table
var secondRow = table.rows[1]; // second row
Then you just get the ID in the typical manner.
console.log(secondRow.id); // "b"
DEMO: http://jsfiddle.net/MErPk/
Answer has been edited
With CSS3 you can use the nth-child selctor. Here the example shows the rowIndex = 2
alert(document.querySelector("table tr:nth-child(2)").id);
In jQuery you can do this with
alert($("table tr:nth-child(2)").attr('id'));
The same syntax nth-child() can be used in CSS
<style>
tr:nth-child(2) {
color: red;
}
</style>

Categories