Javascript add Row, one function for different tables - javascript

I have a few tables like this
<table id="table_1">
<tr>
<td><input type="text" name="date[]"</td>
</tr>
</table>
the number of the <td>'s is very variable.
Currently I'm using a function like this:
function addRow(){
var table = document.getElementById('table_1');
var row = table.insertRow(-1);
var cell1 = row.insertCell(0)
....
cell1.innerHTML="<input type='text' name='date[]' />
}
using this method, it would require a custom function for every type of table.
Is there a way, to add a Line to a table, which is exactly the same as the last row?
In a table with 7 cells, 7 cells would be added, with the right content.
Is this possible in pure JS?

You could do it this way with jQuery:
Edit:
Sorry, I did not see you wanted pure JS.
jQuery
$('button').click(function(){
var table = $(this).prev('table');
var lastrow = $('tr:last-child', table).html();
table.append('<tr>' + lastrow + '</tr>');
});
HTML
<table>
<tr>
<th>Name</th>
<th>Country</th>
<th>Age</th>
</tr>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</table>
<button>Add a row</button>
<table>
<tr>
<th>Meal</th>
<th>Price</th>
</tr>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</table>
<button>Add a row</button>
JS Fiddle Demo

Maybe this is what you need : http://jsfiddle.net/thecbuilder/bx326s31/1/
<input type="button" onclick="cloneRow()" value="Clone Row" />
<input type="button" onclick="createRow()" value="Create Row" />
<table>
<tbody id="tableToModify">
<tr id="rowToClone">
<td><input type="text" name="txt[]"/></td>
<td>bar</td>
</tr>
</tbody>
</table>
function cloneRow() {
var row = document.getElementById("rowToClone"); // find row to copy
var table = document.getElementById("tableToModify"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newID"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function createRow() {
var row = document.createElement('tr'); // create row node
var col = document.createElement('td'); // create column node
var col2 = document.createElement('td'); // create second column node
row.appendChild(col); // append first column to row
row.appendChild(col2); // append second column to row
col.innerHTML = "qwe"; // put data in first column
col2.innerHTML = "rty"; // put data in second column
var table = document.getElementById("tableToModify"); // find table to append to
table.appendChild(row); // append row to table
}
Refer : https://stackoverflow.com/a/1728578/3603806

Related

How do I add a class to a dynamic table's <td> element?

I have a dynamic table, where I need to sum up the values in a particular column, attaching an id property to each row would be the best way to achieve this. I'm only focused on setting and id for each <td> in every table row.
UPDATE: I have all 4 keys in the <td> but I would like each <td> to match what the value is.
JavaScript:
var prodArr = [];
data = [{SKU: "9372983-382L", retail_price: "11.75", list_price: "3.50", product_name: "Tennis balls"}];
function buildTable(data){
var table = document.getElementById('table');
const arr = data;
for(var obj of arr){
var row = document.createElement('tr');
row.setAttribute('id', Object.values(obj)[0]);
//redo this id stuff to maintain insert integrity for each column in the row.
for(var val of Object.values(obj)){
var col = document.createElement('td');
col.textContent = val;
row.appendChild(col);
col.setAttribute('class', Object.keys(obj));
}
var targetCell = row.getElementsByTagName("td");
targetCell[0].setAttribute('class', 'txtSku');
targetCell[1].setAttribute('class', 'txtRetailPrice');
targetCell[2].setAttribute('class', 'txtListPrice');
targetCell[3].setAttribute('class', 'txtProductName');
var input = document.createElement('input');
input.setAttribute('type', 'text');
//input.setAttribute('')
row.appendChild(input);
table.appendChild(row);
}
}
buildTable(data);
HTML:
<table id="table">
<tr>
<th><label>SKU:</label></th>
<th><label>Retail Price:</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tfoot>
<th><label id = "lblTotal">Total:</label><input type="text" name="txtTotal" id = "txtTotal">
<input type="button" value= "Add" id = "addTotals">
</th>
</tfoot>
</table>
When complete I would like the html markup to look like this:
<table id="table">
<tr>
<td><input type="text" name="txtCustomerName" id = "txtCustomerName"></td>
<td><input type="text" name="txtPhone" id = "txtPhone"></td>
<td><input type="text" name="txtEmail" id= "txtEmail"></td>
<td><input type="text" name="txtRopo" id= "txtRopo"></td>
<td><input type="text" name="txtAddress" id= "txtAddress"></td>
</tr>
<tr>
<th><label>SKU:</label></th>
<th><label>Retail Price:</label></th>
<th><label>List Price</label></th>
<th><label>Product Name</label></th>
<th><label>Quantity</label></th>
</tr>
<tr>
<td id="SKU">9372983-382L</td>
<td id="retailPrice">11.75</td>
<td id="listPrice">3.50</td>
<td id="prodName">Tennis balls</td>
<td id="quantity">1</td>
</tr>
<tfoot>
<th><label id = "lblTotal">Total:</label><input type="text" name="txtTotal" id = "txtTotal">
<input type="button" value= "Add" id = "addTotals">
</th>
</tfoot>
</table>
https://codepen.io/Postman507/pen/mdrKZoY
try this
tr.id("id"+i)
It will not be possible to retrieve more than 1 element using ID. Use a class instead. To add just 1 class, you can use HTMLElement.className="class_name". To add more, you can use HTMLElement.classList.add("class_name")
the problem is really your data element. Try to do something like this:
data= {row1:{names:[],ids:[]},
row2:{labels:[]},
row3:{ids[]}}
obviously filling in the arrays with your data. Then in your js you can build your table and add classes and id's as needed.
The solution was using the tables properties to get the rows, then I was able to access the cell data using this outside of the last for loop but inside the first:
var targetCell = row.getElementsByTagName("td");
targetCell[0].setAttribute('class', 'txtSku');
targetCell[1].setAttribute('class', 'txtRetailPrice');
targetCell[2].setAttribute('class', 'txtListPrice');
targetCell[3].setAttribute('class', 'txtProductName');

Trying to Add Row dynamically but getting error

I'm trying to add row consist of three textbox dynamically on click of button with id=btnASize and on click of button with id=btnASizeR want to add a row consist of four textboxes. and on click of button with id=btnWdDelete want to delete the last row which is generated with textboxes and so on.
The three buttons which is mentioned above are generated dynamically and rows with textboxes which will be generated below existing rows are also created on click of those dynamic buttons.Any idea would be appreciated Refer image
$("#btnASize").click(function () {
AddRow($("#SizeR").val(), $("#TolMin").val(), $("#TolMax").val());
$("#SizeR").val("");
$("#TolMin").val("");
$("#TolMax").val("");
});
function insertRow(){}
function AddRow(SizeRange, Tolerancemin,Tolerancemax) {
//Get the reference of the Table's thead element.
var tBody = $("#WireDimTbl > thead> tr")[0];
//Add Row.
row = tBody.insertRow(-1);
//Add Size cell.
var cell = $(row.insertCell(-1));
cell.html(SizeR);
//Add TolMin cell.
cell = $(row.insertCell(-1));
cell.html(TolMin);
//Add TolMax cell.
cell = $(row.insertCell(-1));
cell.html(TolMax);
}
$("#btnWdDelete").click(function () {
var row = $("#SizeR").closest("tr");
//Get the reference of the Table.
var table = $("#WireDimTbl")[1];
//Delete the Table row using it's Index.
table.deleteRow(row[1].rowIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td class='text-left'><strong>Standard Sizes & Tolerances</strong></td>
<td>
<input type='button' ID='btnASize' value='AddSize' />
<input type='button' ID='btnASizeR' value='AddSizeRange' />
<input type='button' ID='btnWdDelete' value='Delete' />
<table ID='WireDimTbl' class='table table-bordered'>
<thead>
<tr>
<th class='text-center'>Size Range (mm)</th>
<th class='text-center'>Tolerance (-)mm</th>
<th class='text-center'>Tolerance (+) mm</th>
</tr>
</thead>
<tr>
<td class='text-center'>
<input type='text' ID='SizeR' value='2.00' />
</td>
<td>
<input type='text' ID='TolMin' value='1' />
</td>
<td>
<input type='text' ID='TolMax' value='1' />
</td>
</tr>
</table>
</td>
</tr>
I prepared this sample to fulfill your requirement, although not a complete solution. You have to write some code by yourself. But this will give you a pretty good idea.
$('#btnAdd').click(function() {
var textboxSize = "<input class='form-control' type='text' class='size range'>";
var textboxTolerance = "<input class='form-control' type='text' class='tolerance'>";
var markup = "<tr><td>" + textboxSize + "</td><td>" + textboxTolerance + "</td></tr>";
$("#myTable tbody").append(markup);
});
$('#btnDelete').click(function() {
$("#myTable tbody>tr:last").remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<input class="btn-primary" id="btnAdd" type="button" value="Add Row">
<input class="btn-primary" id="btnDelete" type="button" value="Delete">
<table class="table" id="myTable">
<thead>
<th>
Size Range
</th>
<th>
Tolerance
</th>
</thead>
<tbody>
</tbody>
</table>
I think there are a few issues with your code.
You call insertRow on an HTMLTableRowElement. insertRow is a HTMLTableElement method, so we need to make sure we're calling it on a HTMLTableElement, instead of a HTMLTableRowElement. To fix this, we'll select the table. We can then use insertRow() on it.
You call $(row.insertCell(-1)) to insert a cell. This is invalid jQuery code. insertCell is a plain JS method for a HTMLTableRowElements, so we need to make sure we're calling it on the appropriate type of element. Specifically, we'll use row.insertCell(), instead of $(row.insertCell(-1)).
The Delete function contains similar errors, but I'll leave that one as is so you can learn by correcting it yourself.
$("#btnASize").click(function() {
AddRow($("#SizeR").val(), $("#TolMin").val(), $("#TolMax").val());
$("#SizeR").val("");
$("#TolMin").val("");
$("#TolMax").val("");
});
function AddRow(SizeRange, Tolerancemin, Tolerancemax) {
//Get the reference of the Table's thead element.
var tBody = $("#WireDimTbl")[0];
//Add Row.
row = tBody.insertRow(-1);
//Add Size cell.
var cell1 = row.insertCell(-1);
$(cell1).text(SizeRange);
//Add TolMin cell.
var cell2 = row.insertCell(-1);
$(cell2).text(Tolerancemin);
//Add TolMax cell.
var cell3 = row.insertCell(-1);
$(cell3).text(Tolerancemax);
}
$("#btnWdDelete").click(function() {
var row = $("#SizeR").closest("tr");
//Get the reference of the Table.
var table = $("#WireDimTbl")[1];
//Delete the Table row using it's Index.
table.deleteRow(row[1].rowIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td class='text-left'><strong>Standard Sizes & Tolerances</strong></td>
<td><input type='button' ID='btnASize' value='AddSize' /><input type='button' ID='btnASizeR' value='AddSizeRange' /><input type='button' ID='btnWdDelete' value='Delete' />
<table id='WireDimTbl' class='table table-bordered'>
<thead>
<tr>
<th class='text-center'>Size Range (mm)</th>
<th class='text-center'>Tolerance (-)mm</th>
<th class='text-center'>Tolerance (+) mm</th>
</tr>
</thead>
<tr>
<td class='text-center'><input type='text' ID='SizeR' value='2.00' /></td>
<td><input type='text' ID='TolMin' value='1' /></td>
<td><input type='text' ID='TolMax' value='1' /></td>
</tr>
</table>
</td>
</tr>

Insert HTML table row clone at index without jquery

I am attempting to insert a row at the index of the addmorebutton td row.
First attempt indeed adds a row at the desired index however not as I would have expected, simply as space vs actually adding a bounded row column box.
How do I insert a new row at the clicked index of td that is empty and is indeed apart of the table?
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('Table').deleteRow(i);
}
function addRow() {
var i = row.parentNode.parentNode.rowIndex;
document.getElementByID('Table').insertRow(i);
}
turkSetAssignmentID();
<script type='text/javascript' src='https://s3.amazonaws.com/mturk-public/externalHIT_v1.js'></script>
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'>
<input type='hidden' value='' name='assignmentId' id='assignmentId' />
<h1>This is a test</h1>
<div id="tablediv">
<input type="button" id="addbutton" value="Add Index" /><br/><br/>
<table id="Table" border="1">
<tr>
<td>Index</td>
<td>Measured Depth</td>
<td>Inclination</td>
<td>Azimuth</td>
<td>Delete?</td>
<td>Add Row?</td>
</tr>
<tr>
<td>1</td>
<td><input size=25 type="text" id="Measured Depth" contenteditable='true'></td>
<td><input size=25 type="text" id="Inclination" contenteditable='true'></td>
<td><input size=25 type="text" id="Azimuth" contenteditable='true'></td>
<td><input type="button" id="delbutton" value="Delete" onclick="deleteRow(this)" /></td>
<td><input type="button" id="addmorebutton" value="Add More Indexs" onclick="addRow.apply(this)" /></td>
</tr>
</table>
</div>
<p><input type='submit' id='submitButton' value='Submit' /></p>
</form>
You could try to add the respective cells to new row, saving the row on a var and the with the appendChild() function. Something like this:
function addRow(row) {
var i = row.parentNode.parentNode.rowIndex + 1;
var nextRow = document.getElementById('Table').insertRow(i);
// Start iterating over all the cells on the row
var cell = nextRow.insertCell(0);
cell.appendChild(document.createTextNode(i));
cell = nextRow.insertCell();
cell = nextRow.insertCell();
cell = nextRow.insertCell();
cell = nextRow.insertCell();
cell = nextRow.insertCell();
input = document.createElement("Input");
input.type = "button";
input.setAttribute("onclick", "addRow(this)");
input.value = "Add More Indexs"
cell.appendChild(input);
}
And of course append on each cell the respective input.
Then maybe you would like to add a function to increase the index number of the rows under the new one...
Also I changed the onclick value on the original button to addRow(this).

Converting user input from html table to JSON with jQuery

I am able to convert a pre populated table with data to JSON object with jQuery. Here is the code:
var header = $('table thead tr th').map(function () {
return $(this).text();
});
var tableObj = $('table tbody tr').map(function (i) {
var row = {};
$(this).find('td').each(function (i) {
var rowName = header[i];
row[rowName] = $(this).text();
});
return row;
}).get();
JSON.stringify(tableObj);
And the html table is like this:
<table>
<thead>
<tr>
<th>Name</th>
<th>E-mail</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>jason</td>
<td>jason#example.com</td>
<td>Developer</td>
</tr>
<tr>
<td>ted</td>
<td>ted#example.com</td>
<td>Bear</td>
</tr>
</tbody>
</table>
Now my task is to actually handle empty table with user inputs. When user load the page, the table is empty with no value, after the user entered the input and click submit, I want to convert the user input data into JSON object and pass it back to back-end.
I am trying to make it happen by warp the table into a form, and add <input> tag in each <td>, something like this:
<form>
<table>
<tbody>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
<tr>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</tbody>
</table>
<button type="submit">Submit</button>
</form>
I try to use the .submit() method from jQuery to make it work but I am getting syntax errors:
$('form').submit(
var header = $('table thead tr th').map(function () {
return $(this).text();
});
var tableObj = $('table tbody tr').map(function (i) {
var row = {};
$(this).find('td').each(function (i) {
var rowName = header[i];
row[rowName] = $(this).text();
});
return row;
}).get();
JSON.stringify(tableObj);
);
How should I change my code to make it work?
That's happening bacause there is no text in the td. You need to find the value of the input.
1) You need to get the input in the td
2) You need to get the value of the input
Also try to look at the editable div
Try this:
row[rowName] = $(this).find('input').val();

creating table within table by pressing button

I currently have a table and in one of the <td>, I have input type of checkbox. where if user clicks on it, it will create different table.
<div style="padding-left:170px;">
<table width="80%" border="1" padding-left:50px>
<tr>
<td>
<table border="1" style="float:left">
<th>Portal01</th>
<tr>
<td style= "padding:12px;" align="left" >
<input type="test0" id = "test0" name="liveDiff" onchange = "expandService()"> blah_0
</td>
<td>
blah_1
</td>
<td>
blah_2
</td>
</tr>
</table>
</td>
</tr>
</table>
I have it set up where if user clicks on checkbox next to blah_0, it should create different table within this table. I am not sure if this is possible with JavaScript and if not, what would be alternate way to approach this situation.
it is possible.
function expandService(){
document.getElementById('the_id_of_the_td_that_will_contain_the_new_table').innerHTML =
'<table><tr>...</tr></table>';
}
Another way is to use appendChild(), here is an example:
function expandService(chkId, tblId, totalRows, totalCols){
var tbl = document.createElement('table');
tbl.id = tblId;
var row, col, spn;
for(var i=0; i<totalRows; i++){
row = document.createElement('tr');
for(var j=0; j<totalCols; j++){
col = document.createElement('td');
spn = document.createElement('span');
spn.innerHTML = 'your-text';
col.appendChild(spn);
row.appendChild(col);
}
tbl.appendChild(row);
}
var chk = document.getElementById(chkId);
// td is the parent of checkbox
chk.parentNode.appendChild(tbl);
}
Sample usage:
<input type="checkbox" id="test0" name="liveDiff" onchange="expandService(this.id, 'your-table-id', 5, 4)">
It creates a table with 5 rows and 4 columns.
This is possible with javascript. One potential way to go is to use innerHTML. Use jQuery or just document.getElementByID to select the element that corresponds to your cell and insert a table inside of it. Here is an example fiddle using your code as a base.
<div style="padding-left:170px;">
<table width="80%" border="1" padding-left:50px>
<tr>
<td>
<table border="1" style="float:left">
<th>Portal01</th>
<tr>
<td id="foo" style= "padding:12px;" align="left" >
<input type="test0" id = "test0" name="liveDiff"> blah_0
</td>
<td>
blah_1
</td>
<td>
blah_2
</td>
</tr>
</table>
</td>
</tr>
</table> ​
js:
var makeTable = function(contents){
return '<table><td>' + contents + '</td></table>'
}
document.getElementById("test0").onchange = function(){
document.getElementById("foo").innerHTML = makeTable("foo")
}
​

Categories

Resources