How to insert input in a new cell with js - javascript

How can I insert an input in a new cell using js?
I try this but doesn't work.
const input = document.querySelector('.option')
console.log(input)
//const id = ele.attributes.name.value
//console.dir(ele, id)
//Add row in table
const table = document.getElementById(id);
const indexRows = table.rows.length;
//console.log(table);
let newRow = table.insertRow(-1)
let newID = newRow.insertCell(0)
let newDesc = newRow.insertCell(1)
let newCell1 = newRow.insertCell(2)
//let newCell2 = newRow.insertCell(3)
newID.innerHTML = indexRows + 1
newDesc = input

Here is a working example. You've forgotten a lot of semicolons.
const table = document.getElementById("t");
const indexRows = table.rows.length;
let newRow = table.insertRow(-1);
let newID = newRow.insertCell(0);
let newDesc = newRow.insertCell(1);
let newCell1 = newRow.insertCell(2);
newID.innerHTML = indexRows + 3;
let input = document.createElement("input");
newDesc.appendChild(input);
newCell1.innerHTML = indexRows + 5;
<table border=1 id="t">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>

Related

How to get table row value into text field in JavaScript..?

I Create a Table Using this code,
<table class="table table-green table-hover" id="tblk"></table>
And I Use This JavaScrip Function (For A Button) to add Rows when I add data in to table,
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
}
When I clicked a table row, I need to get a table Row value into my input text field
This Is my JavaScrip Function to get table rows to value into my text field..,
var table = document.getElementById('tblk'),
rIndex
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function () {
document.getElementById('InputCusomerID').value = this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = this.cells[1].innerHTML
document.getElementById('InputItemID').value = this.cells[2].innerHTML
}
}
But My Code Is Not Working I Can't Get Table Row Value Into My Text Field.
Can You Help Me With That Problem..?
Thank You Very Much..!
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
}
var table = document.getElementById('tblk'),
rIndex
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
document.getElementById('InputCusomerID').value = this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = this.cells[1].innerHTML
document.getElementById('InputItemID').value = this.cells[2].innerHTML
}
}
<table class="table table-green table-hover" id="tblk"></table>
I don't know exactly what you're trying to do, but it's not working because your click listener is being called before your table is populated. See my code.
function addRow() {
var custid = document.getElementById('InputCusomerID').value
var custname = document.getElementById('InputCusomerName').value
var itemid = document.getElementById('InputItemID').value
var table = document.getElementById('tblk')
var row = table.insertRow(0)
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
cell1.innerHTML = custid
cell2.innerHTML = custname
cell3.innerHTML = itemid
setListeners();
}
var table = document.getElementById('tblk'),
rIndex;
function setListeners() {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].addEventListener('click', function (e) {
console.log(e.target);
document.getElementById('InputCusomerID').value = "result: " + this.cells[0].innerHTML
document.getElementById('InputCusomerName').value = "result: " + this.cells[1].innerHTML
document.getElementById('InputItemID').value = "result: " + this.cells[2].innerHTML
});
}
}
addRow();
<input type="text" id="InputCusomerID" value="a" />
<input type="text" id="InputCusomerName" value="b" />
<input type="text" id="InputItemID" value="c" />
<table class="table table-green table-hover" id="tblk"></table>

How to get values of a full <tr> tag in javascript after on change?

I have created a table inside javascript, with 3 input tags
item_name,
item_value and
quantity.
On change quantity input tag, i want to get the values of all 3 input tags in that particular row to calculate the quantity. How to get the full data of <tr> ?
This is my table,
var tr = document.createElement("tr");
var td = document.createElement("td");
let key = entry[0];
let value = entry[1];
const item_name = document.createElement("input");
item_name.setAttribute("id", "item_name[]");
item_name.setAttribute("name", "item_name[]");
item_name.setAttribute("readonly", "readonly");
item_name.value = key;
td.appendChild(item_name);
tr.appendChild(td);
//$('#receipt_details').append(item_name);
const item_value = document.createElement("input");
item_value.setAttribute("id", "item_value[]");
item_value.setAttribute("name", "item_value[]");
item_value.setAttribute("readonly", "readonly");
item_value.value = value.amount;
//$('#receipt_details').append(item_value);
td.appendChild(item_value);
tr.appendChild(td);
const quantity = document.createElement("input");
quantity.setAttribute("id", "quantity[]");
quantity.setAttribute("name", "quantity[]");
quantity.value = 1;
//$('#receipt_details').append(quantity);
td.appendChild(quantity);
tr.appendChild(td);
tbody.appendChild(tr);
table.appendChild(tbody);
$('#receipt_details').append(table);
const total_column = document.createElement("input");
total_column.setAttribute("id", "total_cost[]");
total_column.setAttribute("name", "total_cost[]");
total_column.value = Number(value.amount) * 1;
td.appendChild(total_column);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="receipt_details"></div>
You can try using input event like the following way:
var tr = document.createElement("tr");
var td = document.createElement("td");
let key = 'some key';
let value = {amount:'100'};
const item_name = document.createElement("input");
item_name.setAttribute("id", "item_name[]");
item_name.setAttribute("name", "item_name[]");
item_name.setAttribute("readonly", "readonly");
item_name.value = key;
td.appendChild(item_name);
tr.appendChild(td);
//$('#receipt_details').append(item_name);
const item_value = document.createElement("input");
item_value.setAttribute("id", "item_value[]");
item_value.setAttribute("name", "item_value[]");
item_value.setAttribute("readonly", "readonly");
item_value.value = value.amount;
//$('#receipt_details').append(item_value);
td.appendChild(item_value);
const quantity = document.createElement("input");
quantity.setAttribute("id", "quantity[]");
quantity.setAttribute("name", "quantity[]");
quantity.value = 1;
const total_column = document.createElement("input");
total_column.setAttribute("id", "total_cost[]");
total_column.setAttribute("name", "total_cost[]");
total_column.value = Number(value.amount) * 1;
td.appendChild(total_column);
tr.appendChild(td);
td.appendChild(quantity);
tr.appendChild(td);
const tbody = document.createElement("tbody");
tbody.appendChild(tr);
const table = document.createElement("table");
table.appendChild(tbody);
$('#receipt_details').append(table);
$('table input').on('input', function(){
var parent = $(this).closest('tr');
var value = parent.find('[name="item_value[]"]').val();
var amount = parent.find('[name="quantity[]"]').val();
var total_cost = value * amount;
parent.find('[name="total_cost[]"]').val(total_cost);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="receipt_details"></div>
var value = $('tr').text();
if you can give id or class to the tr then it will be like e.g ( ) then it will be like
var value = $('#tablerow').text();
you can get it like this fiddle
quantity.onchange = function(e) {
var row = {};
$(e.target).closest('tr').find("input:text").each(function() {
row[$(this).attr("name")] = $(this).val();
});
console.log(row);
}

Add Rows and Cols to a HTML Table

I'm trying to figure out how to add a new row to a table using Javascript but I also need to be able to add 3 columns into this table and here is where I am having problems. I can't seem to get it to work. Here is the javascript:
This adds rows with first field being ID entered into the first row but I don't know how to fill in columns.
function myCreateFunction() {
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++) {
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var div1 = document.createElement('div');
div1.innerHTML = "ID";
cell1.appendChild(div1);
div1.contentEditable = true;
}
}
Here is my Table:
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>
try this
function myCreateFunction(thisObj) {
var buttonTr = thisObj.parentNode.parentNode;
var buttonTrHTML = buttonTr.outerHTML;
buttonTr.parentNode.removeChild(buttonTr);
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++)
{
table.innerHTML += "<tr><td>ID</td> <td>First Name</td><td>Last Name</td> <td>Add More</td><tr>";
}
//table.innerHTML += buttonTrHTML ;
table.appendChild(buttonTr );
}
and you need to pass the current Obj as
<button onclick="myCreateFunction(this)">Create row</button>
Try this
function myCreateFunction() {
var table = document.getElementById("myTable");
var rows = table.rows.length;
var row = table.insertRow(rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = "ID";
cell1.contentEditable = true;
cell2.innerHTML = "First Name";
cell2.contentEditable = true;
cell3.innerHTML = "Last Name";
cell3.contentEditable = true;
var but1 = document.createElement('button');
but1.innerHTML = "Create row";
but1.setAttribute("onclick", "myCreateFunction()");
cell4.appendChild(but1);
var but2 = document.createElement('button');
but2.innerHTML = "Delete row";
but2.setAttribute("onclick", "myDeleteFunction()");
cell4.appendChild(but2);
}
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button><button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>
I solved this a bit different. And it works fine (also with deleting rows):
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var maxRows = 10;
if (rowCount < maxRows) {
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[0].cells[i].innerHTML;
}
} else {
alert("Max. Tabs= " + maxRows);
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (chkbox != null && chkbox.checked == true) {
if (rowCount <= 1) {
alert("Min Tabs = 1");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Try following function
function myCreateFunction() {
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
console.log(rowCount)
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = rowCount;
cell2.innerHTML = ""; //put your text/html here
cell2.innerHTML = ""; //put your text/html here
}
put your desired text or html in innerHTML of the respected cell
Also for Pavel's answer your markup is wrong(though I haven't tested the function). The table id 'myTable' should be passed as string.
<button onclick="addRow('myTable')">Create row</button>
could not comment for not having enough reputation
Hope this helps.

How to use javascript/jquery to loop through table?

I have a block of code like below
<tbody class="society_list">
<tr>
<td>1</td>
<td>Dummy</td>
<td>Dummy</td>
<td id="lol0">UPDATE THIS</td>
</tr>
<tr>
.....
</tr>
</tbody>
What I want to do is to loop through the whole table, find the td with an id, get the value of that id, and then update the html inside.
What I have for now(Sorry I'm quite new and I still don't have much idea what to do...)
function update(){
var trs = document.querySelectorAll('.society_list tr');
for(i=0;i<trs.length-1;i++){
trs[i].find('td').each(function(){
//I know I need to do something here but what's that..
});
}
}
Iterate through tds which have id attribute using the has attribute selector.
$('.society_list tr td[id]').each(function(){
var tdID = $(this).attr('id'); // <--- getting the ID here
var result = doSomeMagicWithId(tdID); // <--- doing something
$(this).html(result); // <---- updating the HTML inside the td
});
mate try use
$('#tblOne > tbody > tr').each(function() {...code...});
Here's a plain JavaScript version:
var os=document.getElementsByTagName('td');
for (var i=0;i<os.length;i++){
var o=os[i];
if (o.id){
o.innerHTML="updated "+o.id;
}
}
I'm tired of the argument that jQuery is really simple. Well under the hood it still has to match all the DOM elements. Some form of iteration still takes place. The plain JavaScript version isn't so bad and it doesn't HIDE complexity. And it runs in all browsers, including the IE versions that the jQuery folks deem "irrelevant".
If you know the id attribute, you don't need to loop through table. With jQuery it's so simple:
$('#lol0').text('What you want');
OR:
$('#lol0').html('What you want');
DEMO
function addRow(tableID,index)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.style.backgroundColor = "#FEF0FF";
rowCount = rowCount-1;
//row.id = "tr_add"+rowCount;
var cell1 = row.insertCell(0);
cell1.style.backgroundColor = "red";
cell1.style.align ="center";
var element1 = document.createElement("input");
element1.id = "chk"+(rowCount);
element1.name = "chk"+(rowCount);
element1.type = "checkbox";
//element1.style.textAlign="center";
var element111 = document.createElement("input");
element111.id = "chkbox"+(rowCount);
element111.name = "chkbox"+(rowCount);
element111.type = "hidden";
var element112 = document.createElement("input");
element112.id = "textCopy"+(rowCount);
element112.name = "textCopy"+(rowCount);
element112.type = "hidden";
element112.value ="COPY";
//cell1.innerHTML = "COPY";
cell1.appendChild(element1);
cell1.appendChild(element111);
cell1.appendChild(element112);
cell1.style.textAlign="center";
}
function addRow(tableID,index)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.style.backgroundColor = "#FEF0FF";
rowCount = rowCount-1;
//row.id = "tr_add"+rowCount;
var cell1 = row.insertCell(0);
//cell1.style.backgroundColor = "red";
//cell1.style.align ="center";
var element1 = document.createElement("input");
element1.id = "chk"+(rowCount);
element1.name = "chk"+(rowCount);
element1.type = "checkbox";
//element1.style.textAlign="center";
var element111 = document.createElement("input");
element111.id = "chkbox"+(rowCount);
element111.name = "chkbox"+(rowCount);
element111.type = "hidden";
var element112 = document.createElement("input");
element112.id = "textCopy"+(rowCount);
element112.name = "textCopy"+(rowCount);
element112.type = "hidden";
element112.value ="COPY";
//cell1.innerHTML = "COPY";
cell1.appendChild(element1);
cell1.appendChild(element111);
cell1.appendChild(element112);
cell1.style.textAlign="center";
document.getElementById('hdRowCount').value = rowCount+1;
document.getElementById('btnCopy'+rowCount).onclick = function(){addRow('tableToModify',rowCount);};
}
<table>
<tr>
<td>
<button type="button" name="btnCopy<%=i%>" id="btnCopy<%=i%>" value="Copy" onclick="addRow('tableToModify','<%=i%>');">Copy</button>
</td>
</tr>
</table>

removing textfield in javascript?

I have this problem using javascript whenever I create row and try to remove one, the last row can only removed. here's my javascript
<script>
function createinput(){
var field_area = document.getElementById('fields');
var num = document.forms["zxc"]["set"].value;
for(var count=1;count<=num;count++){
var tr = document.createElement("tr");
var td = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("td");
var td4 = document.createElement("td");
var label = document.createElement("label");
var label2 = document.createElement("label");
var label3 = document.createElement("label");
var label4 = document.createElement("label");
var input = document.createElement("input");
var input2 = document.createElement("input");
var input3 = document.createElement("input");
var input4 = document.createElement("input");
input.id = 'qty[]';
input.name = 'qty[]';
input.type = "text";
input.className = "form-control";
input2.id = 'unit[]';
input2.name = 'unit[]';
input2.type = "text";
input2.className = "form-control";
input3.id = 'articles[]';
input3.name = 'articles[]';
input3.type = "text";
input3.className = "form-control";
input4.id = 'serial_number[]';
input4.name = 'serial_number[]';
input4.type = "text";
input4.className = "form-control";
tr.appendChild(td);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
td.appendChild(label);
td2.appendChild(label2);
td3.appendChild(label3);
td4.appendChild(label4);
label.appendChild(input);
label2.appendChild(input2);
label3.appendChild(input3);
label4.appendChild(input4);
field_area.appendChild(tr);
var removalLink = document.createElement('a');
removalLink.className = "remove";
removalLink.onclick = function(){
field_area.removeChild(tr);
}
removalLink.appendChild(document.createTextNode('Remove Field'));
tr.appendChild(removalLink);
}
}
</script>
And here's my HTML.
<form name="zxc" method="post">
<label><input type="text" id="set" name="set"></label><input type="button" onClick="createinput()" value="create" ></form>
<table width="800" id="fields">
<tr>
<th>Quantity</th>
<th>Unit</th>
<th>Article</th>
<th>Serial</th>
</tr>
</table>
I used a for loop to control how many rows can be created.. I can't solve the problem in removing each rows. I need help please!
UPD Working demo http://jsfiddle.net/tarabyte/5TWsv/2/.
You are creating functions in a loop. They will point the same variable. You need
var makeHandler = function(row) {
return function () {
field_area.removeChild(row);
}
};
...
for(...) {
...
removalLink.onclick = makeHandler(tr);
Then num is of type string. You need to convert it to a number
var num = parseInt(document.forms["zxc"]["set"].value);
And ensure num is actually a number
if(!isNaN(num)) {
And finally IDs have to be unique within document! That's why it is called an "identifier".

Categories