Generate table code( not table) based on input value (HTML, JavaScript) - javascript

I want to generate table code based on two input fields. One input field contains number of rows and another one contains number of columns. There is one more button called submit on click of that I need to generate table code for no of rows / no of columns.
Suppose If gave rows 3 and column 2, then it should generate code like
<table>
<tbody>
<tr>
<td> </td><td> </td>
</tr>
<tr>
<td> </td><td> </td>
</tr>
<tr>
<td> </td><td> </td>
</tr>
</tbody>
</table>
This code I need to save into one string.
Please help me how to do this. I am beginner for JavaScript.

need to save into one string.
var form = document.getElementsByTagName("form")[0];
form["button"].onclick = function() {
var html = "<table><tbody>";
for (var i = 0; i < form["rows"].value; i++) {
html += "<tr>";
for (var j = 0; j < form["columns"].value; j++) {
html += "<td> </td>"
}
html += "</tr>"
}
html += "</tbody></table>";
console.log(html)
}
<form>
<input type="number" min="1" max="10" name="rows" required />rows
<input type="number" min="1" max="10" name="columns" required />columns
<input type="button" name="button" value="create table" />
</form>

I made an example for you here:
JS-FIDDLE
function buildTable() {
var rows = document.getElementById("setRows").value;
var cols = document.getElementById("setCols").value;
var table = "<table>";
table += "<tbody>";
for (i=0;i<rows;i++) {
table += "<tr>";
for (j=0;j<cols;j++) {
table += "<td> </td>";
}
table += "</tr>";
}
table += "</tbody>";
table += "</table>";
document.getElementById("tableHolder").innerHTML=table;
}

Related

Reset input fields when adding a new row to a table using JavaScript

On my HTML page, there is a table inside a form. The table's first row is the labels of the columns, and the rest of the rows contain input text fields.
Under the table, there is a button which operates a JavaScript function which duplicates the first row at the end of the table.
The problem is that the text is also copied from the first row fields to the newly added row fields. Instead, I want to clear the text from the newly added row fields. How can I do that?
This is my code:
<form action="update.php" method="post" enctype="multipart/form-data">
<table id="addresses" class="form" border="1">
<tbody>
<tr>
<p>
<th>
</th>
<th>
<label for='UPDATE_NAME'>Name</label>
</th>
<th>
<label for='UPDATE_NUMBER'>Phone Number (With Country Code)</label>
</th>
<th>
<label>Address (House No., Street, City, State, ZIP Code, P.O. Box)</label>
</th>
</p>
</tr>
<?php
for ($i = 0; $i < count($addresses); $i++) {
$id = str_pad($i, 2, '0', STR_PAD_LEFT);
echo "<tr>";
echo "<p>";
echo "<td>";
echo "<input type='checkbox' name='chk[]' />";
echo "</td>";
echo "<td>";
echo "<input type='text' name='UPDATE_NAME[]' value='".$names[$id]['S']."' />";
echo "</td>";
echo "<td>";
echo "<input type='tel' name='UPDATE_NUMBER[]' value='".$numbers[$id]['S']."' />";
echo "</td>";
echo "<td>";
echo "<input type='text' name='UPDATE_ADDRESS[]' value='".$addresses[$id]['S']."' />";
echo "</td>";
echo "</p>";
echo "</tr>";
}
?>
</tbody>
</table>
<p>
<input type="button" value="Add Address" onClick="addRow('addresses')" />
</p>
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 10) {
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
document.getElementById("APP_UPDATE_NAME[" + rowCount + "]").reset();
} else {
alert("Maximum Branches Number is 10");
}
}
</script>
<input type="submit" class="flat-button form" name="SUBMIT" value="Update Addresses" />
</form>
In the code above, you can see the first row with the labels, and after that, a PHP loop that adds information from a PHP array. After the table, you can see the JavaScript function which adds a row to the table.
What do I need to add to the script so it would be copied without the text from the input fields?
You can set the value of the new row manually instead of copying it. Like so:
newcell.innerHTML = "<input type='...' name='...' value='...' />";
This way you control what goes into the newcell.

Keep state of expansion of a table after page reload

I have got a jsp page with a table.
<table class="table table-striped table-bordered table-hover" id="sample_3">
<thead> <tr><input type=hidden value="hidden value" id="" lass="cls" />
<th>
Order ID
</th>
<th>
Customer Name
</th>
<th>
Delivery Date & Time
</th>
<th>
Amount
</th>
<th>
Payment Method
</th>
</tr>
</thead>
<tbody>
<c:forEach var="order" items="${orderList}" varStatus="status">
<tr id="mainOrderRow_${order.header.orderId}">
<form name="orderItemListForm${order.header.orderId}" id="orderItemListForm${order.header.orderId}" action="processOrder" method="POST">
<input type="hidden" name="orderId" id="orderId" value="${order.header.orderId}" />
<input type="hidden" name="orderAction" id="orderAction" value="" />
<input type="hidden" name="approverNotes" id="approverNotes" value=""/>
<input type="hidden" name="inStockItems" id="inStockItems" value=""/>
<td>
${order.header.orderId}
</td>
<td>
${order.header.user.userName}
</td>
<td>
${order.header.deliveryTime}
</td>
<td>
${order.header.totalAmount.currency}
<fmt:formatNumber value="${order.header.totalAmount.value}" type="number"
maxFractionDigits="2" minFractionDigits="2" />
</td>
<td>
${order.header.paymentMethod}
</td>
</td>
</form>
</tr>
</c:forEach>
</tbody>
</table>
When I click on the '+' on each row, it expands to display the details(taken from the JSON, orderJson) of the table. I've written it using javascript.
function fnFormatDetails(oTable, nTr) {
var aData = oTable.fnGetData(nTr);
selectedOrderId = aData[1];
var orderJsonString = orderMap[''+selectedOrderId];
var orderJson = JSON.parse(orderJsonString);
var Items = orderJson.order.Items;
var sOut = '<div class="row">';
sOut += '<div class="col-md-7"><h3>Order Details for ID: '+selectedOrderId+'</h3><div class="table-responsive"><table class="table table-bordered orderDetails orderDetails">';
sOut += '<thead><tr><th>Product Name</th><th>Quantity</th><th>Price/Unit</th><th>Availability</th><th>Total Price</th></tr></thead>';
sOut += '<tbody>';
var Currency = "";
for(var itemLoop in Items){
sOut += '<tr><td><del>'+Items[itemLoop].ProductName+'</del></td><td><del>'+Items[itemLoop].Quantity+'</del></td><td><del>'+Items[itemLoop].Currency+' '+Items[itemLoop].UnitPrice+'</del></td><td><del> <input type="checkbox" class="inStockItems" name="inStockItems" id="inStockItems" value="'+Items[itemLoop].ItemId+'" disabled> In Stock</del></td><td><del>'+Items[itemLoop].Currency+' '+Items[itemLoop].TotalItemPrice+'</del></td></tr>';
Currency = ''+Items[itemLoop].Currency;
}
sOut += '</tbody>';
sOut += '<tfoot><tr><td> </td><td> </td><td> </td><td> </td><td>'+Currency+' '+orderJson.order.TotalItemsPrice+'</td></tr></tfoot>';
sOut += '</div></div><div class="col-md-5"><div class="col-md-12">';
sOut += '<h3>';
if(orderJson.order.Status == "Submitted" ){
sOut += '<input type="button" value="Accept" class="btn btn-info" onclick="processOrder('+selectedOrderId+','+'\'accept\''+')">';
sOut += '<input type="button" value="Reject" class="btn btn-danger" onclick="processOrder('+selectedOrderId+','+'\'reject\''+')"> ';
}else if(orderJson.order.Status == "Accepted"){
sOut += '<input type="button" value="Ship" class="btn btn-warning" onclick="processOrder('+selectedOrderId+','+'\'ship\''+')">';
}else if(orderJson.order.Status == "Shipped"){
sOut += '<input type="button" value="Deliver" class="btn btn-success" onclick="processOrder('+selectedOrderId+','+'\'deliver\''+')">';
}
sOut += 'Print Delivery Details</h3>';
sOut += '<div class="table-responsive">';
sOut += '<table class="table table-bordered orderSummery">';
sOut += '<tr><td>Customer Address</td><td>'+orderJson.order.Address+'</td></tr><tr><td>Delivery Method</td><td>'+orderJson.order.DeliveryMethod+'</td></tr>';
if (orderJson.order.CustomerNote == null) {
sOut += '<tr><td>Customer's Note</td><td></td></tr>';
} else {
sOut += '<tr><td>Customer's Note</td><td>'+orderJson.order.CustomerNote+'</td></tr>';
}
sOut += '</table>';
sOut += '</div></div></div></div>';
return sOut;
}
Here is the function process order:
function processOrder(orderId, actionName) {
var formName = "orderItemListForm" + orderId;
if (actionName == 'accept') {
document.forms[formName].orderAction.value = actionName;
document.forms[formName].submit();
}
}
}else if(actionName == 'reject'){
if(document.getElementById("t_approverNotes").value == ''){
alert("Please provide a reason for rejection");
document.getElementById("t_approverNotes").focus();
}else{
document.forms[formName].orderAction.value = actionName;
document.forms[formName].approverNotes.value = $.trim($("#t_approverNotes").val());
document.forms[formName].submit();
}
}else {
document.forms[formName].orderAction.value = actionName;
document.forms[formName].submit();
}
}
My problem is, when I click a button(Accept, Reject, Ship, Deliver) on the expanded area and when the page reloads after the form is submitted, the area is collapsed, showing only the rows of the table. I want the area in the expanded form (can't use ajax here as it will cause problems when too many persons are logged in) when the page is reloaded. Any idea how to do it?
You'll have to store the date locally to the user - my suggestion is using localStorage, but you can also use Cookies. When you initialize your app, you'll have to read the state back out of localStorage (or Cookie) and expand the rows that should be expanded.
Here's a quick localStorage example:
var appState = { openRows: [1, 3, 5] }; // example state object with IDs of rows that are expanded
// Storing your app state
if (localStorage) {
localStorage.setItem('appState', JSON.stringify(appState));
}
// Reading your app state
var appState = JSON.parse(localStorage.getItem('appState'));
// Code that expands all the rows that should be expanded

HTML table with editable fields accessed in javascript.

I am trying to build a table that will allow users to change the value of a cell(s) and then "submit" that data
to a JavaScript (only please) method that turns the tables data into a json dataset.
I started by trying to updated the value of just one field. QTY in this case. I am able to loop over the table and get the static values, but I am not able to catch the user input value.
question: What is a JavaScript only (if possible) way to capture user change(able) values from a table?
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).innerHTML;
//alert("qty: " + wty);
qty = qty.substr(oCells.item(2).innerHTML.indexOf('value=') + 7);
qty = qty.substr(0, qty.indexOf('" class='));
//alert(qty);
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
THANK YOU
Instead of selecting the entire td element, retrieve only what you really need using querySelector (or use jQuery if possible). Find the input element and access the value, it's a lot easier than doing all of that unecessary parsing of the inner html of the entire cell.
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).querySelector(".mdl-textfield__input").value;
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
You need to use document.getElementById('value2').value instead of .innerHTML.indexOf('value=')
You're making yourself a lot of work here. You have a table. All you need to do is convert that to JSON. I would suggest you look at the library below that does that in around one line of native java-script.
http://www.developerdan.com/table-to-json/

How to take value from cell in javascript

I have a grid setter in javascript like this :
function AddMdrPymt(){
var f = document.frmPL0011;
var grid = document.getElementById("mdrPymtGrid");
var numRows = grid.rows.length;
grid.insertRow(numRows);
grid.rows[numRows].insertCell(0);
grid.rows[numRows].insertCell(1);
grid.rows[numRows].insertCell(2);
grid.rows[numRows].insertCell(3);
grid.rows[numRows].cells[0].innerHTML = "<input type='checkbox' value='" + curRow + "' name='__mdrPymt' id='__mdrPymt'>";
grid.rows[numRows].cells[1].innerHTML = "<table border='0' align='center'><tr align='center'><td><input type='text' onkeyPress='checkNumber(this)' name='txt_strtAmnt' id='txt_strtAmnt' class='" + txtclass + "' maxlength='18' size='25' fieldName='<%=LangFormatter.getString("PL0011_LoanStartAmnt", true)%>' onblur='checkData(this)' value = '" + val + "' "+dsb+"></td></tr></table>";
grid.rows[numRows].cells[2].innerHTML = "<table border='0' align='center'><tr align='center'><td><input type='text' onkeyPress='checkNumber(this)' name='txt_endAmnt' id='txt_endAmnt' class='portlet-form-input-field' maxlength='18' size='25' fieldName='<%=LangFormatter.getString("PL0011_LoanEndAmnt", true)%>' onblur='checkData2(this)'></td></tr></table>";
curRow += 1;
And this is the grid HTML, the HTML code for the grid tittle, and the function above is function when user press add button
<table width="95%" align="center">
<tr>
<td>
<input name="addBtn" id="addBtn" type=button class='btn' onmouseover="this.className='btnHov'" onmouseout="this.className='btn'" value="<%=LangFormatter.getString("button_add",true)%>" onclick="AddMdrPymt()" tabindex="4">
<input name="delBtn" id="delBtn" type=button class='btn' value="<%=LangFormatter.getString("button_dlt",true)%>" onclick="delMdrPymt()" onmouseover="this.className='btn btnHov'" onmouseout="this.className='btn'" tabindex="5">
</td>
</tr>
<tr>
<td>
<table border="0" cellspacing="1" cellpadding="1" name="mdrPymtGrid" id="mdrPymtGrid" class="grid" width="95%">
<thead class="header">
<th width="1%"></th>
<th width="20%"><%=LangFormatter.getString("PL0011_LoanStartAmnt",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_LoanEndAmnt",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_FixAmntInd",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_FixCashAmnt",true)%></th>
<th width="20%"><%=LangFormatter.getString("PL0011_CashbackLoanAmnt",true)%></th>
</thead>
</table>
</td>
</tr>
<tr>
<td>
<input name="addBtn" id="addBtn" type=button class='btn' onmouseover="this.className='btnHov'" onmouseout="this.className='btn'" value="<%=LangFormatter.getString("button_add",true)%>" onclick="AddMdrPymt()" tabindex="6">
<input name="delBtn" id="delBtn" type=button class='btn' value="<%=LangFormatter.getString("button_dlt",true)%>" onclick="delMdrPymt()" onmouseover="this.className='btn btnHov'" onmouseout="this.className='btn'" tabindex="7">
</td>
</tr>
</table>
How to get value from txt_strtAmnt ?
Thank you
Please use the below code snippet to get the TABLE > TR > TD HTML elemnt value : -
/* To get any TD element value. If one input type inside TD element.
No need to mention the id name as we are getting the value using Tag Name. */
var grid = document.getElementById("mdrPymtGrid");
var tableRows = grid.getElementsByTagName("tr");
for (var j = 0 ; j <= tableRows.length; j++){
var tds = tableRows[j].getElementsByTagName("td");
for (var k = 0 ; k <= tds.length; k++){
var strtAmntVal = tds[k].getElementsByTagName('input')[0].value;
break;
}
}
If you are using grid with multiple rows then solution provided by #Arun will not work,
To make it work
1)find grid element first with document.getElementById('gridid');
2)iterate through its children
3)in that iteration loop find document.getElementById('txt_strtAmnt').value
I am sure that will help you !
also we can achieve through JQuery if you want

Form last value removed after add another field with Javascript

In my html form I can add extra fileds with javascript. But problem is it's removed the last submitted value when I add another field.
For example:
There is a form fileds called: Ingredient and Quantity. I can add another ingredient and Quantity field by click on "Add more" buttion. Ok suppose, I added a new fields and wrote it's value. But if I again click on the "Add more" buttion it's deleted my last fields value.
**Add more = (Ajouter un autre ingrédient)
Html Code:
<table width="700" border="0" cellspacing="0" cellpadding="5" class="table" style="float:">
<td width="180">Ingrédients</td>
<td>
<input type="text"class="tr" name="ingredients[]" id="ingredients" placeholder="Ingredient"/>
</td>
</tr>
<tr>
<td>Quantité</td>
<td><input name="quantity[]" type="text" id="quantity" placeholder="Quantity" class="tr" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" onclick="addmyrow()" name="add" value="Ajouter un autre ingrédient" /><br/><br/> <div id="row"></td>
</tr>
</table>
Javascript Code:
<script language="javascript">
fields = 0;
function addmyrow() {
if (fields != 10) {
document.getElementById('row').innerHTML += "<input type='text' class='tr' name='ingredients[]' id='ingredients' placeholder='Ingredient'/><br/>";
document.getElementById('row').innerHTML += "<input name='quantity[]' type='text' id='quantity' placeholder='Quantity' class='tr' /><br/>";
fields += 1;
} else {
document.getElementById('row').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}
}
</script>
Thanks.
When you append contents like this: document.getElementById('row').innerHTML += ...
you're technically replacing the innerHTML with new HTML.
This causes any changes (i.e., form value changes) to be erased.
The correct way is to create brand new DOM elements and then append those elements. What you're doing now is just appending additional HTML.
Here's the corrected version:
<table width="700" border="0" cellspacing="0" cellpadding="5" class="table" style="float:">
<tr>
<td width="180">Ingrédients</td>
<td>
<input type="text"class="tr" name="ingredients[]" id="ingredients" placeholder="Ingredient"/>
</td>
</tr>
<tr>
<td>Quantité</td>
<td><input name="quantity[]" type="text" id="quantity" placeholder="Quantity" class="tr" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" onclick="addmyrow()" name="add" value="Ajouter un autre ingrédient" /><br/><br/> <div id="row"></div>
</td>
</tr>
</table>
<script language="javascript">
fields = 0;
function addmyrow() {
if (fields != 10) {
var newIngredients = document.createElement('input');
var newQuantity = document.createElement('input');
var brTag = document.createElement('br');
newIngredients.setAttribute('type', 'text');
newQuantity.setAttribute('type', 'text');
newIngredients.setAttribute('placeholder', 'Ingredient');
newQuantity.setAttribute('placeholder', 'Quantity');
newIngredients.setAttribute('name', 'ingredients[]');
newQuantity.setAttribute('name', 'quantity[]');
newIngredients.setAttribute('class', 'tr');
newQuantity.setAttribute('class', 'tr');
document.getElementById('row').appendChild(newIngredients);
document.getElementById('row').appendChild(brTag);
document.getElementById('row').appendChild(newQuantity);
document.getElementById('row').appendChild(brTag);
fields += 1;
} else {
document.getElementById('row').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}
}
</script>
And here's a working fiddle: http://jsfiddle.net/tC7Dm/
changes in innerHTML causes all child DOMs to be destroyed. this link might help
Is it possible to append to innerHTML without destroying descendants' event listeners?
here you go, whoever minusoned me deserves a spoonful of feed.
<script>
function addmyrow() {
var mydiv = document.getElementById("row");
var newcontent = document.createElement('div');
newcontent.innerHTML = "<input type='text' class='tr' name='ingredients[]' id='ingredients' placeholder='Ingredient'/><br/><input name='quantity[]' type='text' id='quantity' placeholder='Quantity' class='tr' /><br/>";
if (fields < 10) {
while (newcontent.firstChild) {
mydiv.appendChild(newcontent.firstChild);
}
fields=fields+1;
}
else {
document.getElementById('row').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}
}
</script>
#Babu, the reason behind this issue is when you get the existing value with innerHTML it doesn't get the value for input dom elements because the value stored in the property not in the attribute. You could find the same in following links
Inner HTML with input values
So rather than using JS you could try jQuery, Below is a working demo
var fields = 0;
function addmyrow() {
if (fields != 10) {
$("#row").append("<input type='text' class='tr' name='ingredients[]' id='ingredients' placeholder='Ingredient' value='' /><br/>");
$("#row").append("<input name='quantity[]' type='text' id='quantity' placeholder='Quantity' class='tr' /><br/>");
fields += 1;
}
else {
$("#row").append("<br />Only 10 upload fields allowed.");
document.form.add.disabled=true;
}
}
Fiddle Demo

Categories