Adding Tables Rows and Cells Dynamically Using Javascript - javascript

I was trying to add a table row with data in my HTML table using Javascript but it seems I it can't add. Why is that?
<html>
<head>
<title>
</title>
<script>
function addUser(){
var tbl = document.getElementById('datatable');
var lastRow = tbl.rows.length;
var iteration = lastRow+1;
var row = tbl.insertRow(lastRow);
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
}
</script>
</head>
<body>
<table border = 1 id = "datatable">
<tr>
<td>ID</td>
<td>NAME</td>
<td>ADDRESS</td>
</tr>
<tr>
<td>1</td>
<td>Something</td>
<td>Something</td>
</tr>
<tr>
<td>2</td>
<td>Foo</td>
<td>bar</td>
</tr>
</table>
<form id = "myForm" onsubmit = "addUser()">
ID:<input type = "text" name = "txtID"><br />
NAME:<input type = "text" name = "txtName"><br />
ADDRESS:<input type = "text" name = "txtAddress"><br />
<input type = "submit" value = "Add Item">
</form>
</body>
</html>

what you need is not to submit a form
just simply an onclick event could help.
<input type = "button" value = "Add Item" onclick="addUser()">

It's because you're submiyting a form. First your AddUSer is called and works, but the page is reloaded and what you see is the initial page.

Related

Remove values from input fields when creating a new table row

I'm trying to create a new role but I want a row where there isn't any value in the textfield.
<form action="Fruits" method="Post" enctype="multipart/form-data">
<table id="myTable">
<c:forEach items="${fruits}" var="val" varStatus="count">
<thead>
<tr>
<th>Fruit</th>
<th>Color</th>
</thead>
<tbody>
<td><input type="text" name="name" id="name" value="${val.name}"></td>
<td><input type="text" name="color" id="color" value="${val.color}"></td>
</tbody>
</table>
<button type="button" class="btn btn-default json-editor-btn-add" onclick="myFunction()">Add</button>
</form>
For now whenever I create a new role, it gives me the values of the first row and fill the text field. Is there a way where I just create a row where it doesnt have any values.
function myFunction(){
var table = document.getElementById("myTable");
var first_tr = table.firstElementChild;
var second_tr = first_tr.nextElementSibling;
var tr_clone = first_tr.cloneNode(true);
var tb_clone = second_tr.cloneNode(true);
table.append(tr_clone);
table.append(tb_clone);
}
I'm expecting a blank field text for all of the column upon creating a row
Instead of cloning previous rows create a row template using a template/string literal that you can insert before the end of the tbody element.
Note: you don't have any rows in your current table's - you just have two cells. You also can't have multiple cells with the same id. Ids are supposed to be unique within a document. If you have to identify cells separately you should use a data attribute instead.
const rowTmpl = `<tr>
<td><input type="text" name="name"></td>
<td><input type="text" name="color"></td>
</tr>`;
const tbody = document.querySelector('tbody');
const button = document.querySelector('button');
button.addEventListener('click', handleClick);
function handleClick(e) {
tbody.insertAdjacentHTML('beforeend', rowTmpl);
}
<table>
<thead>
<tr><td>Fruit</td><td>Color</td></tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" value="Apple" name="name"></td>
<td>
<input type="text" value="Red" name="color">
</td>
</tr>
</tbody>
</table>
<button type="button">Add row</button>
Add below lines in your function.
let array_of_input = tb_clone.querySelectorAll('input');
array_of_input.forEach(cur => {
cur.value = '';
})
Your final function looks like this.
function myFunction() {
var table = document.getElementById("myTable");
var first_tr = table.firstElementChild;
var second_tr = first_tr.nextElementSibling;
var tr_clone = first_tr.cloneNode(true);
var tb_clone = second_tr.cloneNode(true);
table.append(tr_clone);
table.append(tb_clone);
let array_of_input = tb_clone.querySelectorAll('input');
array_of_input.forEach(cur => {
cur.value = '';
})
}

How to dynamically add rows that contains input tag with jquery

I am new in this field, and didn't know where to ask.
I want to make a input form using table. But, i don't know how many rows that needed, so i want to make this table as flexible as it can so users can add more rows as much as their need.
I tried to look at tutorial and answers about this type of question, but i still cannot make my code work.
So, i hope you can help me find the right code for this. Thank you so much.
This is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src = "jquery-3.3.1.min.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("#tambah").click(function () {
var markup = "<tr><td><input type = "number" ID = "no" placeholder = "1"/></td><td><input type = "text" ID = "tahapan" placeholder = "Tahapan 1"/></td><td><input type = "text" ID = "suboutput" placeholder = "Sub-Output 1"/></td></tr>";
$('#table2 tbody').append(markup);
});
});
</script>
<link rel = "stylesheet" type = "text/css" href = "prosesbisnis.css" media = "screen">
<title>
Proses Bisnis Kegiatan Pokok
</title>
</head>
<body>
<div class = "main">
<h1>Proses Bisnis Kegiatan Pokok</h1>
<br>
<br>
<table class = "table">
<tbody>
<tr>
<td class = "col1">Nama Unit Eselon I</td>
<td class = "col2"> : </td>
<td class = "col3">
x
</td>
</tr>
<tr>
<td class = "col1">Nama Satuan Kerja</td>
<td class = "col2"> : </td>
<td class = "col3">
x
</td>
</tr>
<tr>
<td class = "col1">Nama Unit Organisasi</td>
<td class = "col2"> : </td>
<td class = "col3">
x
</td>
</tr>
<tr>
<td class = "col1"><br></td>
<td class = "col2"><br></td>
<td class = "col3"><br></td>
</tr>
<tr>
<td class = "col1">Nama Kegiatan</td>
<td class = "col2"> : </td>
<td class = "col3">
x
</td>
</tr>
<tr>
<td class = "col1">Definisi Kegiatan</td>
<td class = "col2"> : </td>
<td class = "col3">
x
</td>
</tr>
<tr>
<td class = "col1"><br></td>
<td class = "col2"><br></td>
<td class = "col3"><br></td>
</tr>
<tr>
<td class = "col1"><br></td>
<td class = "col2"><br></td>
<td class = "col3"><br></td>
</tr>
</tbody>
</table>
<table id = "table2">
<thead>
<tr>
<th>No</th>
<th>Tahapan</th>
<th>Sub-Output</th>
<th></th>
</tr>
</thead>
<br>
<tbody>
<tr>
<td><br></td>
<td><br></td>
</tr>
<tr>
<td>
<input type = "number" ID = "no" placeholder = "1"/>
</td>
<td>
<input type = "text" ID = "tahapan" placeholder = "Tahapan 1"/>
</td>
<td>
<input type = "text" ID = "suboutput" placeholder = "Sub-Output 1"/>
</td>
</tr>
</tbody>
</table>
<p>
<input type = "button" id = "tambah" value = "Tambah">
</p>
<br>
<br>
<br>
<center>
<a href = "">
<div class = "submit">submit</div>
</center>
<br>
</div>
</body>
</html>
Double quotes is the problem in you script code, either change those into single quotes or replace " with \"
$(document).ready(function(){
$("#tambah").click(function () {
var markup = "<tr><td><input type = \"number\" ID = \"no\" placeholder = \"1\"/></td><td><input type = \"text\" ID = \"tahapan\" placeholder = \"Tahapan 1\"/></td><td><input type = \"text\" ID = \"suboutput\" placeholder = \"Sub-Output 1\"/></td></tr>";
$('#table2 tbody').append(markup);
});
});

How to add dynamic rows with dynamic id in table using jquery

I have a different rows with different columns . I want to add those dynamically.
As my code is
$('.add-invoice-item').click(function (e) {
e.preventDefault();
row += 1;
var elem = $(".temp-tr tr").clone();
elem.find('.alt_date').attr('id', 'invi_date' + row);
$('.invoice-items').append(elem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody class="invoice-items">
</tbody>
<div class="temp-tr hidden-element">
<table>
<tr>
<input type="text" name = "text1"/>
</tr>
<tr>
<input type="text" name = "text2"/>
</tr>
</table>

Can't seem to use element IDs generated dynamically

I want to create a tiered pay calculator utility.
In my Javascript file I dynamically add rows and fields to a table I created with the HTML from a list of names I have in a text input field. The rows consist of a name label column, a text input column to put they're gross earnings in and a calculated pay output column.
I would like for it to update the calculated pay column automatically when I make a change in the text input in the gross earnings column. Although I can trace the element ids through to the calculatePay function I can't seem to use or set their properties. I get the feeling they are not unique as well. Any ideas?
BTW you have to click the update button right now to run the Javascript.
Edit - made some changes per suggestion. Still can't seem to take variables passed to the calculatePay function and simply turn them around and spit them back out into the Pay column of my table.
Edit - SOLVED. The issue was closure, which I didn't understand at first but here's the skinny. To isolate the scope of the variables so they don't get re-wrote every time the loop comes around they need to be declared inside a function that gets recreated with every loop iteration (because Javascript scopes to the function instead of to the code block). Things to note - this does not work if you just declare a nameless function in the middle of your loop. You must return it to a variable(i.e. var buildElement = function(){Yada Yada}();). Also, after the function add () to execute it.
Javascript
function buildTable(){
var artists = document.getElementById("artlist").value;
var names = artists.split(",");
var len = names.length;
var ptable = document.getElementById("payTable");
var rowLength = ptable.rows.length;
for (i=0 ; i < len; i++){
var buildElement = function(){
var row = ptable.insertRow(rowLength);
var nameCell = row.insertCell(0);
var grossCell = row.insertCell(1);
var payCell = row.insertCell(2);
var grossText = document.createElement("input");
grossText.type = "type";
grossText.name = "gtext[]";
grossText.id = "gross" + names[i];
payCell.id = "pay" + names[i];
grossText.onchange = function(){calculatePay(payCell.id, grossText.id);};
grossCell.appendChild(grossText);
nameCell.innerHTML = names[i];
}();
}
}
function resetTable(){
var ptable = document.getElementById("payTable");
var rowLength = ptable.rows.length;
if (rowLength>2){
for (p=rowLength; p>2; p--){
ptable.deleteRow(2);
}
}
buildTable();
}
function calculatePay(target, gross) {
document.getElementById(target).innerHTML = document.getElementById(gross).value;
}
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script src="./js/script.js"></script>
<link rel="stylesheet" href="./css/style.css" />
</head>
<body>
<div>
<table id="payTable">
<tr>
<th colspan=3 class="hdr">
Calculator
</th>
</tr>
<tr>
<th class="hdr">
Name
</th>
<th class="hdr">
Gross
</th>
<th class="hdr">
Pay
</th>
</tr>
</table>
</div>
<div>
<table>
<tr>
<th colspan=3 class="hdr">
SETTINGS
</th>
</tr>
<tr>
<th colspan=3 class="hdr">
Breakpoints
</th>
</tr>
<tr>
<td>Break 1 at $
<input type="text" name="break1" id="break1" value="300"/>
</td>
<td>
</td>
<td>Break 2 at $
<input type="text" name="break2" id="break2" value="900"/>
</td>
</tr>
<tr>
<th colspan=3 class="hdr">
Percentage levels
</th>
</tr>
<tr>
<td>
Below break 1:
<input type="text" size="4" name="per1" id="per1" value="50"/>%
</td>
<td>
Between breaks 1 and 2:
<input type="text" size="4" name="per2" id="per2" value="60"/>%
</td>
<td>
Over break 2:
<input type="text" size="4" name="per3" id="per3" value="70"/>%
</td>
</tr>
<tr>
<td>
Artists:
<input type="text" name="artlist" id="artlist" value="Brian,Eric,Christie,Cynthia,Shawn"/>
</td>
<td>
</td>
<td class="hdr">
<button onclick="resetTable()">Update</button>
</td>
</tr>
</div>
</body>
</html>
The issue was closure, which I didn't understand at first but here's the skinny. To isolate the scope of the variables so they don't get re-wrote every time the loop comes around they need to be declared inside a function that gets recreated with every loop iteration (because javascript scopes to the function instead of to the code block). Things to note - this does not work if you just declare a nameless function in the middle of your loop. You must return it to a variable(i.e. "var buildElement = function(){Yada Yada}();"). Also, after the function add () to execute it.
Javascript
function buildTable(){
var artists = document.getElementById("artlist").value;
var names = artists.split(",");
var len = names.length;
var ptable = document.getElementById("payTable");
var rowLength = ptable.rows.length;
for (i=0 ; i < len; i++){
var buildElement = function(){
var row = ptable.insertRow(rowLength);
var nameCell = row.insertCell(0);
var grossCell = row.insertCell(1);
var payCell = row.insertCell(2);
var grossText = document.createElement("input");
grossText.type = "type";
grossText.name = "gtext[]";
grossText.id = "gross" + names[i];
payCell.id = "pay" + names[i];
grossText.onchange = function(){calculatePay(payCell.id, grossText.id);};
grossCell.appendChild(grossText);
nameCell.innerHTML = names[i];
}();
}
}
function resetTable(){
var ptable = document.getElementById("payTable");
var rowLength = ptable.rows.length;
if (rowLength>2){
for (p=rowLength; p>2; p--){
ptable.deleteRow(2);
}
}
buildTable();
}
function calculatePay(target, gross) {
document.getElementById(target).innerHTML = document.getElementById(gross).value;
}
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script src="./js/script.js"></script>
<link rel="stylesheet" href="./css/style.css" />
</head>
<body>
<div>
<table id="payTable">
<tr>
<th colspan=3 class="hdr">
Calculator
</th>
</tr>
<tr>
<th class="hdr">
Name
</th>
<th class="hdr">
Gross
</th>
<th class="hdr">
Pay
</th>
</tr>
</table>
</div>
<div>
<table>
<tr>
<th colspan=3 class="hdr">
SETTINGS
</th>
</tr>
<tr>
<th colspan=3 class="hdr">
Breakpoints
</th>
</tr>
<tr>
<td>Break 1 at $
<input type="text" name="break1" id="break1" value="300"/>
</td>
<td>
</td>
<td>Break 2 at $
<input type="text" name="break2" id="break2" value="900"/>
</td>
</tr>
<tr>
<th colspan=3 class="hdr">
Percentage levels
</th>
</tr>
<tr>
<td>
Below break 1:
<input type="text" size="4" name="per1" id="per1" value="50"/>%
</td>
<td>
Between breaks 1 and 2:
<input type="text" size="4" name="per2" id="per2" value="60"/>%
</td>
<td>
Over break 2:
<input type="text" size="4" name="per3" id="per3" value="70"/>%
</td>
</tr>
<tr>
<td>
Artists:
<input type="text" name="artlist" id="artlist" value="Brian,Eric,Christie,Cynthia,Shawn"/>
</td>
<td>
</td>
<td class="hdr">
<button onclick="resetTable()">Update</button>
</td>
</tr>
</div>
</body>
</html>

I'm trying to add some rows to an HTML table, but it's failing

Note: this is meant to be a community wiki post
The following code using simple dom methods fails to add rows to the table. What's the issue?
<html>
<head>
<title>Javascript Test</title>
<script>
function addRow() {
var mytable = document.getElementById('mytable');
var row = document.createElement('tr');
var cell = document.createElement('td');
var text = document.createTextNode('This is a row');
cell.appendChild(text);
row.appendChild(cell);
mytable.appendChild(row);
}
</script>
</head>
<body>
<form action="#">
<table id="mytable">
<tr>
<td>This is a row</td>
</tr>
</table>
<input type="button" onclick="addRow()" value="Add A Row"/>
</form>
</body>
</html>
The issue at hand here is that the <table> element's correct structure is not present. When dealing with tables, the basic structure is:
<table>
<thead>
<tr>
<th>Heading for the table</th>
</tr>
</thead>
<tbody>
<tr>
<td>A row of data</td>
</tr>
</tbody>
</table>
The logic is that when dealing with tables, you want to keep the labels of the columns, and the actual data separate. Because most browsers fill in the <tbody> as part of the process of fixing broken HTML, few people realize this. When the browser sees you adding a <tr>, it doesn't know if you're trying to add it to the <thead> or the <tbody>, so it fails.
The following shows the correct method for adding the rows:
<html>
<head>
<title>Javascript Test</title>
<script>
function addRow() {
var mytbody = document.getElementById('mytbody');
var row = document.createElement('tr');
var cell = document.createElement('td');
var text = document.createTextNode('This is a row');
cell.appendChild(text);
row.appendChild(cell);
mytbody.appendChild(row);
}
</script>
</head>
<body>
<form action="#">
<table id="mytable">
<tbody id="mytbody">
<tr>
<td>This is a row</td>
</tr>
</tbody>
</table>
<input type="button" onclick="addRow()" value="Add A Row"/>
</form>
</body>
</html>
Any additional row needs to be added then take the first child of tableID and then use appendChild() method:
var tbl=document.getElementById("tbl");
var row=document.createElement("tr");
var cel=document.createElement("td");
cel.innerHTML='sometext';
row.appendChild(cel);
tbl.children[0].appendChild(row);

Categories