guys, I am going to develop a simple primary code to get data from the user and add to the table. I have already done the mission but there is some problem I need to ask.
I want to put my operation element (Edit | Delete) also in a cell just like entered first name and last name.
I know how to use "td" for first and last name but I dunno how to add "td" element to put (Edit | Delete) also in a cell of my table
function AddStudents(event){
var x = document.getElementById('fname').value ;
var y = document.getElementById('lname').value ;
console.log("LINE 1");
var ftd = document.createElement('tr');
var ft = document.createElement('td');
var text = document.createTextNode(fname.value);
ft.appendChild(text);
console.log("LINE 2");
var nt = document.createElement('td') ;
var text2 = document.createTextNode(lname.value);
nt.appendChild(text2);
var ot = document.createElement('a');
var neu = document.createElement('td') ;
var od = document.createElement('a');
var sp = document.createElement('a');
ot.innerHTML = ' Edit' ;
od.innerHTML = ' Delete';
sp.innerHTML = ' | ' ;
ot.href = "#" ;
od.href = "#" ;
console.log("LINE 3");
ftd.appendChild(ft)
ftd.appendChild(nt)
ftd.appendChild(ot)
ftd.appendChild(sp)
ftd.appendChild(od)
console.log("LINE 4");
document.getElementById("students").appendChild(ftd);
}
and this my html code :
<input type="text" id="fname" placeholder="First Name">
<input type="text" id="lname" placeholder="Last Name">
</br>
</br>
<button id="add" onclick="AddStudents(this)">Add Student</button>
<h3>List Of Students</h3>
<table id="students" cellpadding = "7px" text-align = "center" border="1">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Operation</td>
</tr>
<tbody></tbody>
</table>
You will need to add the edit and delete links to a td and then append the td to your table.
To do this create a td element, create the links, create a span for the bar and then append the links and span to your td. Now you have a proper table cell which you can append to the table.
As an aside, I recommend you use more descriptive variable names so other people can understand your code easier. It looks like this is likely an assignment your professor would also be able to give you help.
var td = document.createElement('td');
var editLink = document.createElement('a');
var deleteLink = document.createElement('a');
var span = document.createElement('span');
editLink.innerHTML = 'Edit';
editLink.href="#";
deleteLink.innerHTML = 'Delete';
deleteLink.href = "#";
span.innerHTML = '|';
td.appendChild(editLink);
td.appendChild(span);
td.appendChild(deleteLink);
Here is some code which does that, but ensure you understand why this creates a table cell instead of just copy pasting it.
You can simply put a <button> in a <td> element directly:
<input type="text" id="fname" placeholder="First Name">
<input type="text" id="lname" placeholder="Last Name">
</br>
</br>
<button id="add" onclick="AddStudents(this)">Add Student</button>
<h3>List Of Students</h3>
<table id="students" cellpadding = "7px" text-align = "center" border="1">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Operation</td>
<td><button class="" id="btnEdit">Edit</button></td>
<td><button class="" id="btnDelete">Delete</button></td>
</tr>
<tbody></tbody>
</table>
If you're using something like Bootstrap then you can also enter classes where I left empty quotation marks to style the button how you'd like.
You can do this in a better way using jQuery
function AddStudents(){
$("#notification").html('');
var fname= $("#fname").val();
var lname=$("#lname").val();
if(fname!='' && lname!=''){
$("#students tbody").append("<tr>");
$("#students tbody").append("<td>"+fname+"</td>");
$("#students tbody").append("<td>"+lname+"</td>");
$("#students tbody").append("<td><a href='#' class='btnedit'>Edit</a> | <a href='#' class='btndelete'>Delete </a></td>");
$("#students tbody").append("</tr>");
}
else{
$("#notification").html('Please enter First Name and Last Name');
}
}
$(document).on("click",".btnedit",function(){
//Implement Edit functionality here
alert('edit');
});
$(document).on ("click",".btndelete",function(){
//Implement delete functionality here
alert('delete');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='notification'></div>
<input type="text" id="fname" placeholder="First Name">
<input type="text" id="lname" placeholder="Last Name">
</br>
</br>
<button id="add" onclick="AddStudents()">Add Student</button>
<h3>List Of Students</h3>
<table id="students" cellpadding = "7px" text-align = "center" border="1">
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
<td>Operation</td>
</tr></thead>
<tbody></tbody>
</table>
I added event handling for your Edit and Delete links since it is created runtime.
Related
I made a listener to attatch an id "selectedRow" to the row a user has clicked on. The intent from there is be able to manipulate the data in that row; Previously i was using content editable however I'm trying to make it more obvious to the user that they are editing a row (this is for a project) so i've created an editing panel to do so. I've however ran in to some problems with a lot of data being returned as undefined when using .innerHTML when sending the TD to the input boxes.
I've tried using .HTML instead
$('tr').click(function() {
if(document.getElementById("SELECTEDROW")) {
var oldRow = document.getElementById("SELECTEDROW");
oldRow.classList.remove("selected");
$("#SELECTEDROW").removeAttr('id');
}
$(this).attr('id', 'SELECTEDROW');
selectedRow = document.getElementById("SELECTEDROW");
table = selectedRow.parentNode;
console.log("Row " + selectedRow.childNodes[1].innerHTML + " Selected");
selectedRow.classList.add("selected");
editRow();
});
function editRow() {
var currentTD = selectedRow.childNodes;
var inputs = document.getElementById("inputs").childNodes;
var i = 0;
for (i = 0; i < currentTD.length; i++) {
inputs[i].innerHTML = currentTD.html;
}
console.log('Now Editing:' + currentTD[1].innerHTML);
document.getElementById("editingPanel").style.display = "block";
document.getElementById("content").style.height = "49%";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Role</th>
<th>Address</th>
<th>Phone</th>
<th>Email</th>
<th>Password</th>
</tr>
<tr>
<td>1</td>
<td>Bill Robbins</td>
<td>Conductor</td>
<td>12, Caldrow Ave, Plymouth, Pl21XE</td>
<td>01921202384</td>
<td>XxbillyboyxX#bossman.com</td>
<td>CaTsRbAe1967</td>
</tr>
<tr>
<td>2</td>
<td>Kat Robbins</td>
<td>Admin</td>
<td>12, Caldrow Ave, Plymouth, Pl21XE</td>
<td>019232042454</td>
<td>katrobs#gmail.com</td>
<td>thR33mel0ns</td>
</tr>
</table>
</div>
<div id="editingPanel">
<div id="inputFields">
<form id="inputs">
<input id="input1" type="text" name=""/>
<input id="input2" type="text" name="">
<input id="input3" type="text" name="">
<input id="input4" type="text" name="">
<input id="input5" type="text" name="">
<input id="input6" type="text" name="">
<input id="input7" type="text" name="">
<input id="input8" type="text" name="">
</form>
</div>
<div id="editButtons">
<button onclick="addRow()">New Row</button>
<button onclick="editRow()">Save Row</button>
<button onclick="removeRow()">Delete Row</button>
</div>
</div>
The expected output would be for each td's text to be copied into the input boxes.
You need to get the children properly. You also need to assign the text to the value property of the input, not its innerHTML
function editRow() {
// You need to get elements by tag name, not childNodes
var currentTD = selectedRow.getElementsByTagName("td");
// You need to get elements by tag name, not childNodes
var inputs = document.getElementById("inputs").getElementsByTagName("input");
var i = 0;
for (i = 0; i < currentTD.length; i++) {
console.log(inputs[i]);
console.log(currentTD[i]);
// set the "Value" of an input box, not its "innerHTML"
// also you need to apply the [i] to the currentTD because it is a list
inputs[i].value = currentTD[i].innerHTML;
}
You can try this:
$("body").on("click","tr",function(){ //Just in case you are going to use dynamic content, because the click method doesn't work on dynamically created/added elements
for(let i=0;i<7;i++){
$("#input"+(i+1)).val($(this).children()[i].innerHTML); //You are using jQuery for a reason, to simplify code, so avoid using unnecessary JS where you can by using simplified jQuery
}
});
I have run to a problem with my JavaScript, I'm new to javascript and have just started integrating it with my web application. I have my javascript here:
<script type="text/javascript">
function addRow()
{
var table = document.getElementById("datatable"),
newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
name = document.getElementById("form").value,
amount = document.getElementById("amount").value;
delete1 = delete1 = '<input type="button" class="btn btn-danger" class="glyphicon glyphicon-trash"id="delete" value="Delete" onclick="deleteRow(this)">';
cell1.innerHTML = name;
cell2.innerHTML = amount;
cell3.innerHTML = delete1;
}
function findTotal(){
var arr = document.querySelectorAll("#datatable td:nth-child(2)");
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
</script>
This addRow Function here serves as my function in adding a cell each type I click "add entry" Here's a bit of my HTML:
<div class="col-md-5" style="display: inline-block; ">
<div class="jumbotron">
<h2>Type in Nature of Collection...</h2>
<form>
<input class="form-control input-lg" id="form" list="languages" placeholder="Search" type="text" required>
<br>
<input class="form-control input-lg" id="amount" list="languages" placeholder="Amount" type="number" required>
<br>
<button onclick="addRow(); return false;">Add Item</button>
</form>
<table id="datatable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Nature of Collection</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<h6> <label>Date:<span></span>
</label>{{date}}</h6>
<h3><fieldset disabled>
<label>Total </label>
<input type = "text" name = "total" id="total"><br></p>
</fieldset></h3>
</div><!-- COL5 END -->
I just took out the HTML codes that are involved with this problem.
I am using addRow() to add each function. The Second column gets a numeric value. For example. 200.00 or 232 r 2.2 What I wanted to do is to get the total while I'm adding it real-time. I have inspected the adding of cells in the developer options in the Mozilla browser it shows that the digits are falling to each of the tr's second td.
So I used var arr = document.querySelectorAll("#datatable td:nth-child(2)");
in my totaling function hoping that I would get the list and evaluate it. However I am unable to do this, there's nothing showing in my total UI.
or.. Am I really getting my amounts in the using that?
This worked when I was implementing it using checkboxes so I know how it would work. Every time I add a value it shows on the total box whenever something gets added. But here it's different. I found an answer that says nth-child gets non-live object list. Should I make the objects live before I can evaluate it in the total?
I'm really stuck at this part. If you have any ideas on how to fix this please do help me. or if you could give me an alternative way to add cells then totaling it real-time that would also help.
I could make do with the submission type, but the page gets reloaded and it will be a hassle for the user to scroll down again. This part of the app, when you add a cell it just pops there without the page reloading, as to why I used javascript to implement this function.
Here are pics of how it works:
Console shows:
Any help is appreciated. Thank you very much!
function addRow()
{
var table = document.getElementById("datatable"),
newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
name = document.getElementById("form").value,
amount = document.getElementById("amount").value;
delete1 = delete1 = '<input type="button" class="btn btn-danger" class="glyphicon glyphicon-trash"id="delete" value="Delete" onclick="deleteRow(this)">';
cell1.innerHTML = name;
cell2.innerHTML = amount;
cell3.innerHTML = delete1;
findTotal();
}
function findTotal(){
var arr = document.querySelectorAll("#datatable td:nth-child(2)");
var tot=0;
for(var i=0;i<arr.length;i++){
var enter_value = Number(arr[i].textContent) //id u want do parseInt(enter_value)
if(enter_value)
tot += Number(arr[i].textContent);
}
document.getElementById('total').value = parseInt(tot);
}
<div class="col-md-5" style="display: inline-block; ">
<div class="jumbotron">
<h2>Type in Nature of Collection...</h2>
<form>
<input class="form-control input-lg" id="form" list="languages" placeholder="Search" type="text" required>
<br>
<input class="form-control input-lg" id="amount" list="languages" placeholder="Amount" type="number" required>
<br>
<button onclick="addRow(); return false;">Add Item</button>
</form>
<table id="datatable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Nature of Collection</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<h6> <label>Date:<span></span>
</label>{{date}}</h6>
<h3><fieldset disabled>
<label>Total </label>
<input type = "text" name = "total" id="total"><br></p>
</fieldset></h3>
</div><!-- COL5 END -->
This should work.
Not the best code but a hot fix for yours.
I recomend you to look into html data- attributes
function addRow()
{
var table = document.getElementById("datatable"),
newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
name = document.getElementById("form").value,
amount = document.getElementById("amount").value;
delete1 = delete1 = '<input type="button" class="btn btn-danger" class="glyphicon glyphicon-trash"id="delete" value="Delete" onclick="deleteRow(this)">';
cell1.innerHTML = name;
cell2.innerHTML = amount;
cell3.innerHTML = delete1;
findTotal();
}
function findTotal(){
var arr = document.querySelectorAll("#datatable td:nth-child(2)");
var tot=0;
for(var i=0;i<arr.length;i++){
tot += parseInt(arr[i].innerHTML);
}
document.getElementById('total').value = tot;
}
<div class="col-md-5" style="display: inline-block; ">
<div class="jumbotron">
<h2>Type in Nature of Collection...</h2>
<form>
<input class="form-control input-lg" id="form" list="languages" placeholder="Search" type="text" required>
<br>
<input class="form-control input-lg" id="amount" list="languages" placeholder="Amount" type="number" required>
<br>
<button onclick="addRow(); return false;">Add Item</button>
</form>
<table id="datatable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Nature of Collection</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<h6> <label>Date:<span></span>
</label>{{date}}</h6>
<h3><fieldset disabled>
<label>Total </label>
<input type = "text" name = "total" id="total"><br>
</fieldset></h3>
</div><!-- COL5 END -->
This is the faulty code:
var arr = document.querySelectorAll("#datatable td:nth-child(2)");
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
In here, arr is a collection of DOM nodes, matching #datatable td:nth-child(2) selector. You're trying to sum up their value properties. However, <td> elements do not have a value. You might want to try getting their innerText property:
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].innerText))
tot += parseInt(arr[i].innerText);
}
Note you're closing a </p> you never opened just after the total field. There might be other problems with your script, but this one caught my eye.
See it working here. (I've stripped it down to minimum).
I have a button that the user clicks on to add a new row to the bottom of an input table. I would like this to also increment the id. So the next row would have desc2, hours2, rate2 and amount2 as the id. Is there a way to do this in the JavaScript function.
Also - just want to check my logic on this. After the user completes the filled out form, I will be writing all the data to a mysql database on two different tables. Is this the best way to go about this? I want the user to be able to add as many lines in the desc_table as they need. If this is the correct way to be going about this, what is the best way to determine how many lines they have added so I can insert into the db table using a while loop?
JS file:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
}
HTML:
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Thank you!
Check this code.After appending the row it counts the number of rows and and then assigns via if condition and incremental procedure the id's:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
for(var i=1;i<rows.length;i++){
if(rows[i].children["0"].children["0"].id.match((/desc/g))){
rows[i].children["0"].children["0"].id='desc'+i;
}
if(rows[i].children["1"].children["0"].id.match((/hours/g))){
rows[i].children["1"].children["0"].id='hours'+i;
}
if(rows[i].children["2"].children["0"].id.match((/rate/g))){
rows[i].children["2"].children["0"].id='rate'+i;
}
if(rows[i].children["3"].children["0"].id.match((/amount/g))){
rows[i].children["3"].children["0"].id='amount'+i;
}
}
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Please change variable names for more descriptive. :)
Example solution...
https://jsfiddle.net/Platonow/07ckv5u7/1/
function new_line() {
var table = document.getElementById("desc_table");
var rows = table.getElementsByTagName("tr");
var row = rows[rows.length - 1];
var newRow = rows[rows.length - 1].cloneNode(true);
var inputs = newRow.getElementsByTagName("input");
for(let i=0; i<inputs.length; i++) {
inputs[i].id = inputs[i].name + rows.length;
}
var textarea = newRow.getElementsByTagName("textarea")[0];
textarea.id = textarea.name + rows.length;
table.appendChild(newRow);
}
Note that I removed/edited below fragment.
x.style.display = "";
r.parentNode.insertBefore(x, r);
You could do this a lot easier with jquery or another dom manipulation language, but with vanilla JS here's an example of simply looping through the new row's inputs & textarea and incrementing a counter to append.
var count = 1;
function new_line() {
count++;
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
// update input ids
var newInputs = Array.from(x.getElementsByTagName('input'))
.concat(Array.from(x.getElementsByTagName('textarea')));
newInputs.forEach(function(input) {
var id = input.getAttribute('id').replace(/[0-9].*/, '');
input.setAttribute('id', id + count);
});
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
I have been able to make this work as it adds into <div></div> tags now I want to remove this array numbers 0,1,2,3 and feed the data into <div></div> tags in HTML, How can this be done, How do I make it insert inside the div tags
<html>
<head></head>
<title>Js test</title>
<h1>Js Test</h2>
<body>
<script type="text/javascript">
var data = new Array();
function addElement(){
data.push(document.getElementById('ins_name').value);
data.push(document.getElementById('gpa').value);
data.push(document.getElementById('da').value);
document.getElementById('ins_name').value='';
document.getElementById('gpa').value='';
document.getElementById('da').value='';
display();
}
function display(){
var str = '';
for (i=0; i<data.length;i++)
{
//str+="<tr><td>" + data[i] + "</td></tr>";
"<tr>
<td align=center width=176>Institution </td>
<td align=center>GPA</td>
<td align=center width=187>Degree Awarded</td>
</tr>"
"<tr>
<td align=center width=176> </td>
<td align=center> </td>
<td align=center width=187> </td>
</tr>"
}
document.getElementById('display').innerHTML = str;
}
</script>
<form name="jamestown" id="jamestown" method="post" action="samris.php" />
Institution : <input type="text" name="ins_name" id="ins_name" /></br>
GPA : <input type="text" name="gpa" id="gpa" /></br>
Degree Awarded : <input type="text" name="da" id="da" /></br>
</p>
<input type="button" name="btn_test" id="btn_test" value="Button Add Test" onClick='addElement()'; /></br>
</form>
<div id=display></div>
</body>
</html>
Since you've been adding more and more requirements in the comments, the innerHTML += "" approach stops working.
I advice you to create elements using document.createElement and add them to your document using Node.appendChild.
It's not really an answer to the initial question, but I figured it helps you more than continuing conversation in the comments. Maybe you can edit your question to reflect the additional requirements.
Let me know if there's stuff I used that you don't yet understand. Happy to elaborate!
var inputIds = ["ins_name", "gpa", "da"];
var inputElements = inputIds.map(getById);
var tbody = getById("display");
// Create a new row with cells, clear the inputs and add to tbody
function addRow() {
// Create a row element <tr></tr>
var row = document.createElement("tr");
inputElements.forEach(function(input) {
// For each input, create a cell
var td = document.createElement("td");
// Add the value of the input to the cell
td.textContent = input.value;
// Add the cell to the row
row.appendChild(td);
// Clear the input value
input.value = "";
});
// Add the new row to the table body
tbody.appendChild(row);
}
getById("btn_test").addEventListener("click", addRow);
// I added this function because document.getElementById is a bit too long to type and doesnt work with `map` without binding to document
function getById(id) {
return document.getElementById(id);
}
Institution : <input type="text" name="ins_name" id="ins_name" /><br>
GPA : <input type="text" name="gpa" id="gpa" /><br>
Degree Awarded : <input type="text" name="da" id="da" /><br>
<input type="button" id="btn_test" name="btn_test" value="Add Test"/><br>
<table>
<thead>
<tr>
<th>Institution</th>
<th>GPA</th>
<th>Degree</th>
</tr>
</thead>
<tbody id="display">
</tbody>
</table>
function addData() {
var rows = "";
var ID = document.getElementById("id").value;
var Task = document.getElementById("task").value;
rows += "<tr><td>" + ID + "</td><td>" + Task + "</td></tr>";
var tbody = document.querySelector("#table tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
<body>
<form onsubmit="" method="POST">
ID:
<input type="text" id="id" required>New task:
<br>
<textarea id="task" required></textarea>
<br>
<input type="submit" value="Add" onclick="addData()">
</form>
<h3>Task Table</h3>
<div id="excell">
<table id="table" cellspacing="0px" cellpadding="25px" text-align="center">
<thead>
<tr>
<td>ID</td>
<td>Task</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
I'm learning Javascript and I'm trying to implement a small "ID and Task" table, but somehow it only works when I enter only 1 type of data such as only ID or only task, when I enter 2 data at the same time, nothing happens. I'd be grateful if you tell me what is the problem and how can I fix it. Thank you.
Here's my HTML
<body>
<form onsubmit="" method="POST">
ID:
<input type="text" id="id" required>
New task:<br>
<textarea id="task" required></textarea>
<br>
<input type="submit" value="Add" onclick="addData()">
</form>
<h3>Task Table</h3>
<div id = "excell">
<table id = "table" cellspacing = "0px" cellpadding = "25px" text-align = "center">
<thead>
<tr>
<td>ID</td>
<td>Task</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
and here's my JS
function addData() {
var rows = "";
var ID = document.getElementById("id").value;
var Task = document.getElementById("task").value;
rows += "<tr><td>" + ID + "</td><td>" + Task + "</td></tr>";
var tbody = document.querySelector("#table tbody");
var tr = document.createElement("tr");
tr.innerHTML = rows;
tbody.appendChild(tr)
}
Actual problem with your code is, you have used Submit button. Normally when a submit button is hit it post the data to action property of the form tag, which means transfer the page to next; if action property is not given, it give flickering effect and stay with current page and made all components with empty. The same is happen in your code also.
Better Change the code
<input type="Submit" value="Add" onClick="addData();"/>
into
<input type="BUTTON" value="Add" onClick="addData();"/>
and try its worked fine.