insertRow() not working with FOR loop - javascript

I am trying to write a JavaScript code to add multiple rows according to the number submited in an input text box. I am trying to do that by using a FOR loop but for some reason it does not work. Can you explain to me why it does not insert as many rows as the value from input text box??? Here is my code:
<!DOCTYPE html>
<html>
<head>
<br><meta charset=utf-8 />
<title>Insert rows in a Table</title>
</head>
<body>
<table id="table" border="1">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
</table><br>
<form>
Type in a number:<input id="input" type="text" value=""}>
<input type="button" onclick="insert_Row()" value="add row(s)">
</form><br/>
<p id="p"></p>
<script>
var tableId = document.getElementById("table");
function insert_Row(){
var input = document.getElementById("input").value;
var number = Number(input);
for(i=0;i<number;i++){
var ii = i+1;
var newTR = table.insertRow(i);
var newTD1 = newTR.insertCell(i);
var newTD2 = newTR.insertCell(ii);
newTD1.innerHTML = "Row " + i + " Cell "+ i;
newTD2.innerHTML = "Row " + i + " Cell "+ ii;
};
};
</script>
</body>
</html>

The problem is irrespective of the row number, cells should start from 0,1,2 and so on which is not happening in your code. For the 0th iteration your code works fine, but later on, the cells do not start from 0. Hence the problem
Fix: Since you plan to have only 2 cells for each row, do it like this:
var tableId = document.getElementById("table");
function insert_Row() {
var input = document.getElementById("input").value;
var number = Number(input);
for (i = 0; i < number; i++) {
var j = 0; // First Cell
var k = 1; // Second Cell
var newTR = table.insertRow(i);
var newTD1 = newTR.insertCell(j);
newTD1.innerHTML = "Row " + i + " Cell " + j;
var newTD2 = newTR.insertCell(k);
newTD2.innerHTML = "Row " + i + " Cell " + k;
};
};
<table id="table" border="1">
</table>
<br>
<form>
Type in a number:
<input id="input" type="text" value=""/>
<input type="button" onclick="insert_Row()" value="add row(s)">
</form>
<br/>
<p id="p"></p>

The issue is with your document.getElementById declarations.
Also, it sounds like you want to insert the rows at the end of your table. In which case, your code will look like this.
var table = document.getElementById("table");
var numRows = document.querySelectorAll("tr").length;
function insert_Row(){
var input = document.getElementById("myInput").value;
var number = Number(input);
for (var i = numRows; i < number; i++) {
var ii = 0;
var ij = 1;
var newTR = table.insertRow(i);
var newTD1 = newTR.insertCell(ii);
var newTD2 = newTR.insertCell(ij);
newTD1.innerHTML = "Row " + (i + 1) + " Cell "+ (ii +1);
newTD2.innerHTML = "Row " + (i + 1) + " Cell "+ (ij + 1);
};
};
To use document.getElementById, you need to add an id attribute to your input tag like so.
<input id="myInput" type="button" onclick="insert_Row()" value="add row(s)">
Here is the updated fiddle
http://jsfiddle.net/vgwk00zm/2/

Related

How to generate a TABLE in js with the flexibility to width/height/row/column

I'm trying to put in options to be able to input column/row/width/height for my Javascript table..but can't seem to get it work. I have absolutely no coding background.. just got into this course 1 month ago..
I tried looking up everywhere but I can't make sense of what is happening..
<html>
<body>
<form>
<p>No. of Cols: <input type="text" name="cols" id="cols" value="3" />
</p>
<p> No. of Rows<input type="text" name="rows" id="rows" value="3" />
Sample Cell Data <input type="text" id="sample" /> </p>
<p> Cell Height (in pixels)<input type="text" id="height" />
Cell wdith in pixels<input type="text" id="wdith" /> </p>
<Button onClick="generate()">Generate Table</button>
<button onClick="deleteTable()">Clear Table</button>
</form>
<hr />
<p id=generatedTable> </p>
</body>
<script>
function generate()
var myTable = document.getElementById("generatedTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.create Element('TBODY');
table.appendChild(tableBody);
for (var y=0; y<num_rows; y++)
{
var num_rows = document.getElementById('rows').value;
tableBody.appendChild(tr);
var num_cols = document.getElementById('cols').value;
for (var x=0; x<num_cols; x++)
{
var td = document.createElement('TD');
td.width = 10; td.height = 10; td.align = "center";
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id",cellID.toString());
td.addEventListener("click", function(){cellClicked(this);});
// ... research and add other mouse events!!!
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
}
myTable.appendChild(table);
}
}
</script>
</html>
In the code, you provided the num_rows and num_cols is the number of column/row, width/height is related styles; so, you don't want to do it in javascript, you can provide some styles like this:
.custom-width{
/* some style */
}
then in your code after creating a td:
var td = document.createElement('TD');
td.classList.add('custom-width')
// do other stuff and append it
I think that the best solution to your problem is to use Bootstrap 4 grid; it permit to create responsive tables using only div as rows and columns. In this way you can manage very easily width and height with col-size class.
Install: https://getbootstrap.com/docs/4.3/getting-started/introduction/
Bootstrap grid: https://getbootstrap.com/docs/4.0/layout/grid/
var num_rows and var num_rows should be out of both the for loop.
tr should be declared inside the first for loop because you cannot append to it till it is declared.
for simplicity, I have set the num_rows and 'num_rows' to 5.
for guidance in future how to work with tables you can refer
Traversing an HTML table with JavaScript
var element = document.getElementById("div1");
debugger;
var tableBody = document.createElement('TBODY');
var table= document.createElement('table')
table.appendChild(tableBody);
var num_rows = 5;
var num_cols =5;
for (var y=0; y<5; y++)
{
//document.getElementById('rows').value;
var tr =document.createElement('tr')
//document.getElementById('cols').value;
for (var x=0; x<5; x++)
{
var td = document.createElement('TD');
td.width = 10; td.height = 10; td.align = "center";
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id",cellID.toString());
td.addEventListener("click", function(){cellClicked(this);});
// ... research and add other mouse events!!!
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
tableBody.appendChild(tr);
}
//myTable.appendChild(table);
element.appendChild(table)
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
td
{
border:1px solid;
}
<div id="div1">
</div>

How can i multiply or add the values of a dynamic javascript input field

The input field are been generated by javascript. I want to pick each value no matter how many input field I generate...so I can use the values for some calculations.
<form action="{{ route('addmorePost') }}" method="POST">
<div class="table-responsive">
<span id="result"></span>
<table class="table table-bordered">
<thead>
<tr>
<th width="55%">Sales Representative</th>
<th width="15%">Target per day</th>
<th width="15%">Monthly day</th>
<th width="10%"> + </th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="target[]" class="form-control target" id="target" oninput="calc()">
</td>
<td><span id="sum1" onchange="add()">0</span> </td>
<td> - </td>
</tr>
</tbody>
<tfoot>
<tr>
<th>
</th>
<th> Total</th>
<th><span id="sumx">0</span> </th>
</tr>
</tfoot>
<script>
function add() {
var ven1 = document.getElementById('sum1').innerHTML;
var valuey = document.getElementById('result1').innerHTML || 0;
console.log(ven1);
console.log(valuey);
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey);
}
</script>
</table>
</button>
</form>
BELOW IS THE JAVASCRIPT FOR GENERATED INPUT FIELDS
<script type="text/javascript">
$(document).ready(function(){
var postURL = "http://localhost/bcwater/public/addmore";
var i=1;
$('.addRow').on('click', function(){
i++;
addRow();
});
function addRow(){
var tr = '<tr class="dynamic-added">'+
'<td>'+
'</td>'+
'<td><input type="text" name="target[]" id="target2" class="form-control" oninput="calc()" /> </td>'+
'<td><span id="result1">0</span> </td>'+
'<td> - </td>'+
'</tr>';
$('tbody').append(tr);
};
$('tbody').on('click','.remove', function(){
$(this).parent().parent().remove();
});
});
THIS IS THE CODEI HAVE TRIED TO GET THE VALUES , MULTIPLY THEM BY 26 AND DISPLAY THE ANSWER ON sum1
<script>
function calc(){
var value1 = document.getElementById('target').value || 0;
document.getElementById('sum1').innerHTML = parseInt(value1 * 26);
var value2 = document.getElementById('target2').value;
document.getElementById('result1').innerHTML = parseInt(value2 * 26);
var ven1 = document.getElementById('sum1').innerHTML;
var valuey = document.getElementById('result1').innerHTML || 0;
console.log(ven1);
console.log(valuey);
document.getElementById("products").disabled = false;
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey);
}
</script>
PLEASE HELP!!!...WHAT AM I DOING WRONG
From your code every time you call addRow() the ID is always target2.
To auto change the ID, have a variable that holds the current ID and concatenate the string, you can make use of the var i.
$(document).ready(function(){
var postURL = "http://localhost/bcwater/public/addmore";
var i=1;
$('.addRow').on('click', function(){
i++;
addRow(i);
});
function addRow(i){
var tr = '<tr class="dynamic-added">'+
'<td>'+
'</td>'+
'<td><input type="text" name="target[]" id="target' + i + '" class="form-control" oninput="calc()" /> </td>'+
'<td><span id="result' + i + '">0</span> </td>'+ //This is modified to attach the current index to result
'<td> - </td>'+
'</tr>';
$('tbody').append(tr);
};
$('tbody').on('click','.remove', function(){
$(this).parent().parent().remove();
});
});
The i variable should always hold the index for the last row added
To multiply the values you have to make use of the same i variable, the function calc() should look like this, i suggest you rename i to something descriptive:
function calc(){
var value1 = document.getElementById('target').value || 0;
document.getElementById('sum1').innerHTML = parseInt(value1 * 26);
for(var j = 1; j <= i; j++) {
var value2 = document.getElementById('target' + j).value;
document.getElementById('result' + j).innerHTML = parseInt(value2 * 26); // This is to target the result span that corresponds to the input value
}
var ven1 = document.getElementById('sum1').innerHTML;
var valuey = document.getElementById('result1').innerHTML || 0;
console.log(ven1);
console.log(valuey);
document.getElementById("products").disabled = false;
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey);
}
Thank u..i was able to do it this way...after i increate the value of the id like this
id="target' + i + '" and also span
so i use the below code to get the values manually...not the best option, but it solved my problem cos i dont need more than three input fields
function calc(){
var value1 = document.getElementById('target').value || 0;
document.getElementById('sum1').innerHTML = parseInt(value1 * 26);
var value2 = document.getElementById('target2').value;
document.getElementById('result2').innerHTML = parseInt(value2 * 26);
document.getElementById("products").disabled = false;
var value2 = document.getElementById('target3').value;
document.getElementById('result3').innerHTML = parseInt(value2 * 26);
var ven1 = document.getElementById('sum1').innerHTML || 0;
var valuey = document.getElementById('result2').innerHTML || 0;
var valuenew = document.getElementById('result3').innerHTML || 0;
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey) + parseInt(valuenew);
}
</script>

rearrange/decrement row and cell id after deleting dynamically added rows javascript

I have a table with a default row and I am adding new rows dynamically with a button click, incrementing the ID of the tr and the innerText of the first td with a counter. I am trying to rearrange the ID's after deleting a row. Suppose I have 5 rows and I delete row nr 3, the 4th row should have the ID 3, and the 5th should have ID 4 etc. And also whena adding new rows it should rearrange the row ID's.
Here what I have so far. I have been trying but with no success or I dont get the desired results. Could anyone help me in the right direction?
<table class="table text-center table-borderless" id="rfqTable" style="font-size: 12px;">
<thead>
<tr>
<th>Item</th>
<th>Descr</th>
<th>Quantity</th>
<th>One Time</th>
<th>Supplier</th>
</tr>
</thead>
<tbody>
<tr id="1" class="tableRow">
<td class="item">1</td>
<td><textarea name="item[1]" rows="3" cols="90" maxlength="500"></textarea></td>
<td><input type="number" name="amount[1]"/></td>
<td><input type="checkbox" name="oneTime[1]" value="1"></td>
<td><input type="checkbox" name="supplier[1]" value="1"></td>
</tr>
</tbody>
</table>
Adding row:
var counter = 1;
var limit = 5;
document.getElementById("newItemBoxButton").addEventListener("click", function(){
if (counter == limit)
{
alert("Max row is 5!");
}
else
{
counter ++;
var table = document.getElementById("rfqTable");
var row = table.insertRow(-1);
row.setAttribute('id', counter );
var cell0 = row.insertCell(0);
cell0.innerHTML = counter;
cell0.setAttribute('id', 'item');
var cell1 = row.insertCell(1);
cell1.innerHTML = '<textarea name="item[' + counter + ']" rows="3" cols="90" maxlength="500"></textarea>';
var cell2 = row.insertCell(2);
cell2.innerHTML = '<input type="number" name="amount[' + counter + ']" style="width: 50px;"/>';
var cell3 = row.insertCell(3);
cell3.innerHTML = '<input type="checkbox" name="oneTime[' + counter + ']" value="1">';
var cell4 = row.insertCell(4);
cell4.innerHTML = '<input type="checkbox" name="supplier[' + counter + ']" value="1">';
var cell5 = row.insertCell(5);
cell5.innerHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
});
Deleting row:
function deleteRow(rowid)
{
var row = document.getElementById(rowid);
var table = row.parentNode;
while (table && table.tagName != 'TABLE')
{
table = table.parentNode;
if (!table)
{
return;
}
table.deleteRow(row.rowIndex);
counter--;
}
var table = document.getElementById('rfqTable');
var trRows = table.getElementsByTagName('tr');
var tdRows = table.getElementsByTagName('td');
for (var i = 0; i < trRows.length; i++)
{
trRows[i].id = counter;
}
for (var i = 0; i < tdRows.length; i++)
{
document.getElementById("item").innerText = counter;
}
}
After deleting a row, all the row id's turn into the same id, and the td item doesnt change at all.
In deleteRow function, why you have added this -
for (var i = 0; i < trRows.length; i++) {
trRows[i].id = counter;
}
You are assigning same value to all rows since your counter variable is not changing. It should be like this -
trRows[i].id = i + 1; // added + 1 since you want to start from 1 not 0
ok, I got a fix. I targeted the first column of every row and changed that value. For loop has to start at 1, else it will also target the first th. So now the IDs will be rearranged after deleting a row and the value will always start at 1.
var table = document.getElementById('rfqTable');
for (var i = 1; i < table.rows.length; i++)
{
var firstCol = table.rows[i].cells[0];
firstCol.innerText = i;
}

Javascript query fix

I am new to Javascript programming, can anyone help me on fixing the below script. In this script, I am getting some input from the user and then adding it to an array. Finally displaying it in a table. But for some reason, the last entry in the array overwrites all the previous entries in it.
var CountryList = new Array();
var arrNum = 0;
function initCountry(name, capital) {
this.name = name;
this.capital = capital;
//Comments
//alert(arrNum);
CountryList.push(this);
document.getElementsByName("countryName")[0].value = "";
document.getElementsByName("capitalCity")[0].value = "";
}
function funcSaveButton() {
var txt1 = document.getElementsByName("countryName")[0];
var txt2 = document.getElementsByName("capitalCity")[0];
initCountry(txt1.value, txt2.value);
//alert(txt1.value +":"+ txt2.value);
arrNum++;
}
function displayList() {
var i;
document.write("<table border='2'>");
document.write("<tr> <td> Country Name </td> <td> Capital City </td> </tr>")
for (i = 0; i < CountryList.length; i++) {
//alert("i="+i);
document.write("<tr>");
document.write("<td> " + CountryList[i].name + "</td>");
document.write("<td> " + CountryList[i].capital + "</td>");
document.write("</tr>");
}
document.write("</table>");
}
Country Name: <input type="text" name="countryName" required></input>
<Br> Capital City: <input type="text" name="capitalCity" required></input><br><br>
<input type="button" name="saveButton" value="Save Details!!" onclick="funcSaveButton()"></input>
<input type="button" name="displayButton" value="Display Country List!!" onclick="displayList()"></input>
You are pushing window object to CountryList
inside function this object is window.
use this CountryList.push({name:name,capital:capital});
var CountryList = new Array();
var arrNum = 0;
function initCountry(name, capital)
{
this.name = name;
this.capital = capital;
//Comments
//alert(arrNum);
CountryList.push({name:name,capital:capital});
document.getElementsByName("countryName")[0].value = "";
document.getElementsByName("capitalCity")[0].value = "";
}
function funcSaveButton()
{
var txt1 = document.getElementsByName("countryName")[0];
var txt2 = document.getElementsByName("capitalCity")[0];
initCountry(txt1.value, txt2.value);
//alert(txt1.value +":"+ txt2.value);
arrNum++;
}
function displayList()
{
console.log(CountryList);
var i;
document.write("<table border='2'>");
document.write("<tr> <td> Country Name </td> <td> Capital City </td> </tr>")
for(i=0;i<CountryList.length;i++)
{
//alert("i="+i);
document.write("<tr>");
document.write("<td> "+ CountryList[i].name + "</td>");
document.write("<td> "+ CountryList[i].capital + "</td>");
document.write("</tr>");
}
document.write("</table>");
}
Country Name: <input type="text" name="countryName" required></input><Br>
Capital City: <input type="text" name="capitalCity" required></input><br><br>
<input type="button" name="saveButton" value="Save Details!!" onclick="funcSaveButton()"></input>
<input type="button" name="displayButton" value="Display Country List!!" onclick="displayList()"></input>

how to make new table columns dynamically

At the moment only a cell is added to theclicked link's row and the bottom columns are not shown.
i would like the js code below to work such that if i click onany link say link 2 none of the top cells in the column are displayed apart from starting with the one inline with this link 2 and those below in the newly created column.
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function addColumn(element) {
var tr = element.parentElement.parentElement;
var td = document.createElement("td");
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
tr.appendChild(td);
}
</script>
I have been trying out this code:
function appendColumn() {
var tbl = document.getElementById('my_table');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < tbl.rows.length; i++) {
var newcell = tbl.rows[i].insertCell(tbl.rows[i].cells.length);
for (var j = 0; j < colCount; j++) {
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
}
but it doesn't do it.
jquery is also welcome
jsFiddle
If I correctly understood you need something like this:
function addColumn(element) {
var tr = element.parentElement.parentElement;
var trs = tr.parentElement.querySelectorAll( "tr" );
var trN = nInArray( trs, tr );
var tds = trs[ trs.length - 1 ].querySelectorAll( "td" );
var tdNextN = parseInt( tds[ tds.length - 1 ].querySelector( "input" ).name.match( /BX(\d+)_NAME\[\]/ )[ 1 ] );
if ( trN == 0 ) {
tdNextN++;
}
for ( var i = 0; i < trs.length; i++ ) {
var td = document.createElement( "td" );
if ( i >= trN ) {
td.innerHTML = "<label>Name" + tdNextN + "</label>";
td.innerHTML += "<input type=\"text\" required=\"required\" name=\"BX" + tdNextN + "_NAME[]\" />";
}
trs[ i ].appendChild( td );
}
}
function nInArray( array, object ) {
for ( var i = 0; i < array.length; i++ ) {
if ( array[ i ] === object ) {
return i;
}
}
return -1;
}
And that's what I think is required:
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
}
item.appendChild(td);
});
}
Fiddle with this
Take a look of jquery
$('#datble').find('tbody').append('<tr><td>TD 1</td><td>TD 2</td></tr>');
//or you can prepend
$('#datble').find('tbody').prepend('<tr><td>TD 1</td><td>TD 2</td></tr>');
You can also try this throught jquery:
var html = "";
after
html += '<tr><td>TD</td></tr>';
or
html += '<tr>';
html += '<td>';
html += 'TD';
html += '</td>';
html += '</tr>';
and after all do this
$('#' + table_id ).append(html);

Categories