Append data to html table - javascript

I'm trying to add more data to the table below using JavaScript.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Home Page</title>
<script type="text/javascript" src="assets/style.js"></script>
</head>
<body>
<br><br><br><br><br>
<input type="text" id="personName" autofocus>
<button type="button" onclick="addData();">Append Information</button> <br><br><br><br><br>
<table>
<tr>
<th>Client Name</th>
</tr>
<tr>
<td>James Bond 007</td>
</tr>
<div id="addDataHere">
</div>
</table>
</body>
</html>
style.js Used is below:
function addData(){
var personName = document.getElementById("personName").value;
//console.log(personName);
var getOlderInformation = document.getElementById("addDataHere").innerHTML;
document.getElementById("addDataHere").innerHTML = getOlderInformation + "<tr><td>" + personName + "</tr></td>";
}
Expected Output Results:
Client Names James Bond 007 Tom Cruise ............ ............ ............ ............

This should get you started.
function addData() {
var personName = document.getElementById("personName").value;
var newRow = document.createElement("tr");
var newCell = document.createElement("td");
newCell.innerHTML = personName;
newRow.append(newCell);
document.getElementById("rows").appendChild(newRow);
document.getElementById("personName").value = '';
}
<input type="text" id="personName" autofocus>
<button type="button" onclick="addData();">Append Information</button> <br><br><br><br><br>
<table>
<tr>
<th>Client Name</th>
</tr>
<tbody id="rows">
<tr>
<td>James Bond 007</td>
</tr>
</tbody>
</table>
You were on the correct path, but an important note is that you were trying to use a div inside of a table. A table has very specific structure that has to be matched if you want it to render properly.
You are able to put div elements inside of a td or a th, but not inside of the table element itself. Check out this link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table

you can use a list to match what you need here's the code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Home Page</title>
</head>
<body>
<input type="text" id="personName" autofocus>
<button type="button" onclick="addData();">Append Information</button>
<p>Client Name</p>
<ul id="mylist">
<li>James Bond 007</li>
</ul>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
and the use adddata() function code like this
`function addData(){
var mylist=document.getElementById("mylist");
var personName=document.getElementById("personName").value;
var node = document.createElement("LI");
var textnode = document.createTextNode(personName);
node.appendChild(textnode);
mylist.appendChild(node);
}`
I hope this helps you :)

You can use an approach similar to what you are attempting: getting the innerHTML, appending some new html, and then replacing the innerHTML. But, you need to get the innerHTML of your table (not the element you nested inside of it).
For example (replaced your button onclick with an event listener).
const personName = document.getElementById('personName');
const appendButton = document.getElementById('appendButton');
const nameTable = document.getElementById('nameTable');
appendButton.addEventListener('click', (event) => {
let content = nameTable.innerHTML;
content += '<tr><td>' + personName.value + '</td></tr>';
nameTable.innerHTML = content;
});
<input type="text" id="personName" autofocus>
<button type="button" id="appendButton">Append Information</button>
<table id="nameTable">
<tr>
<th>Client Name</th>
</tr>
<tr>
<td>James Bond 007</td>
</tr>
</table>
Depending on the complexity of what you are doing, it may be faster to go the createElement / appendChild route suggested in the other answers if you also use use createDocumentFragment. Another example:
appendButton.addEventListener('click', (event) => {
const frag = document.createDocumentFragment();
const tr = document.createElement('tr');
const td = document.createElement('td');
td.appendChild(document.createTextNode(personName.value));
tr.appendChild(td);
frag.appendChild(tr);
nameTable.appendChild(frag);
});
<input type="text" id="personName" autofocus>
<button type="button" id="appendButton">Append Information</button>
<table id="nameTable">
<tr>
<th>Client Name</th>
</tr>
<tr>
<td>James Bond 007</td>
</tr>
</table>

You want to use appendchild. Check this out for some
Good examples https://www.w3schools.com/jsref/met_node_appendchild.asp . You want to loop through the data adding a row to a table , one row at a time

Related

I want to show the total rows beside the search and make search code work in python?

I created a table and I want to do a search for two columns (code and name) so when the user enters any letter or number of name, code columns it shows all row names containing that letter
and I want to show the total rows of my table next to search box.
in HTML
<input type="text" class="form-control" onkeyup="searchrecords" id="searchtext" placeholder="Search" aria-label="Text input with dropdown button">
<h6 class="mt-3 mx-4">Total: </h6>
</div>
</div>
<table class="table table-striped " id="table1">
<thead>
<tr class="feed-bg text-white ">
<th>ID</th>
<th>Employee Code</th>
<th>Employee Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for i in data_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{i.employee_code}}</td>
<td>{{i.employee_name}}</td>
<td>{{i.email}}</td>
</tr>
{% endfor %}
</tbody>
</table>
In JS I did the search code but it does not work!
function searchrecords()
{
var input,table,tr,td,filter;
input=document.getElementById("searchtext");
filter=input.value.toUpperCase();
table=document.getElementById("table1");
tr=table.getElementsByTagName("tr");
for(i=0;i<tr.length;i++)
{
td=tr[i].getElementsByTagName("td")[0];
if(td)
{
textdata=td.innerText;
if(textdata.toUpperCase().indexOf(filter)>-1)
{
tr[i].style.display="";
}
else
{
tr[i].style.display="none";
}
}
}
}
I made an example for you here. Maybe it helps.
const input = document.getElementById("searchtext");
const rowNum = document.getElementById("row-num");
const table = document.getElementById("table1");
const tr = Array.from(table.getElementsByTagName("tr"));
function renderRowNr() {
rowNum.innerHTML = tr.filter((row) => row.style.display !== "none").length;
}
function resetRows() {
tr.forEach((row) => (row.style.display = "inherit"));
}
function searchrecords() {
resetRows();
input.value &&
tr
.filter((row) => {
return !Array.from(row.children)
.map((cell) => {
return cell.textContent
.toUpperCase()
.includes(input.value.toUpperCase());
})
.some((cell) => cell === true);
})
.forEach((row) => (row.style.display = "none"));
renderRowNr();
}
function init() {
resetRows();
renderRowNr();
input.addEventListener("change", () => searchrecords());
}
init();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<label>Filter: </label>
<input id="searchtext" />
<p>row number: <span id="row-num"></span></p>
<table class="table table-striped" id="table1">
<tbody>
<tr>
<td>1</td>
<td>abc</td>
<td>Lokrum</td>
<td>email1</td>
</tr>
<tr>
<td>2</td>
<td>def</td>
<td>Lara</td>
<td>email2</td>
</tr>
<tr>
<td>3</td>
<td>ghi</td>
<td>Lora</td>
<td>email3</td>
</tr>
</tbody>
</table>
<script src="app.js"></script>
</body>
</html>
It looks as though your code loops through all the rows, then for each row checks the first cell in the row (td[0]) against the input field. It looks as though the first cell in the row contains a counter so presumably will not match the input text?
Try sticking in some console.log statements in your loop to check what is happening (or step through in a debugger)
It would be easier if you shared all of the relevant generated HTML (including 'searchtext' input). Assuming you are happy with the HTML that has been generated, then the final HTML will be more useful rather than the django markup.
You should probably remove the python and django tags from your question as it seems that your issue is purely with HTML/JS

Why ismy nameValue, amountValue and dateValue undefined?

I try to append a tr element to a tbody element, it works but when the tr is shown, the td is undefined, NaN and undefined. I try to get the value from the input elements and submit the tr of data to tbody.
Do you guys have any idea of where i went wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expense tracker remake</title>
</head>
<body>
<h1>Expense tracker</h1>
<div class="bold" id="name">Name of Item: </div> <input type="text">
<div class="bold" id="amount">Amount: </div> <input type="text">
<div class="bold" id="date">Date: </div> <input type="date">
<button id="submit">Submit</button> <button id="clear">Clear all</button>
<table>
<thead>
<th>Name</th>
<th>Amount</th>
<th>Date</th>
</thead>
<tbody id="tbody">
</tbody>
</table>
<script>
var tbody = document.getElementById("tbody");
var name = document.getElementById("name");
var amount = document.getElementById("amount");
var date = document.getElementById("date");
var clear = document.getElementById("clear");
var submit = document.getElementById("submit");
submit.addEventListener("click",function(){
var nameValue = name.value;
var amountValue = amount.value;
var dateValue = date.value;
var tr = document.createElement("tr");
tr.innerHTML += "<td>"+nameValue+ " </td><td>"+ + amountValue+ "</td><td>" + dateValue+ "</td>";
tbody.appendChild(tr);
console.log(name.value);
})
</script>
You have added an extra + in html string which you are using to append tr element.
tr.innerHTML += "<td>"+nameValue+ " </td><td>" + amountValue+ "</td><td>" + dateValue+ "</td>";
You made two mistakes:
Your name, amount and date elements are a divs, not an inputs, so when you trying to read from name.value you are trying to read from empty div.
Some words in javascript are reserved and sometimes when you using those your code could works in strange way. One of those words is name. Source.
The working demo of your code you can find here: jsFiddle.net.
As you can see, I've just pointed to input instead of div (by calling nextElementSibling because your input is a next element of your div) and changing variables names for avoiding name conflicts. Also, I have removed unnecessary doubled plus signs from tr.innerHtml += ....

How to enable editing table cell data on multiple rows?

How can I enable data editing inside a table cell with javascript on multiple row.
I have written a code that gets the cell data and replace it with a text box that has previous data on it and saves the data in to the cell after you finished editing. But I want to make it possible with multiple table rows. Btw. the table will be Php generated.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<title>EDIT USER</title>
<script>
function edit() {
var a = document.getElementById("fname").innerHTML;
var b = document.getElementById("lname").innerHTML;
document.getElementById("fname").innerHTML='<input id="fnamefld" type="text" value="'+a+'"'+' />';
document.getElementById("lname").innerHTML='<input id="lnamefld" type="text" value="'+b+'"'+' />';
document.getElementById("edit_btn").disabled=true;
document.getElementById("done_btn").disabled=false;
}
function done() {
document.getElementById("done_btn").disabled=true;
document.getElementById("edit_btn").disabled=false;
var a = document.getElementById("fnamefld").value
var b = document.getElementById("lnamefld").value
document.getElementById("fname").innerHTML=a;
document.getElementById("lname").innerHTML=b;
}
</script>
</head>
<body>
<table border="0">
<th>First Name</th>
<th>Last Name</th>
<th>Edit?/Done?</th>
<tr>
<td id="fname">User fname</td>
<td id="lname">User lname</td>
<td>
<button id="edit_btn" onclick="edit()">Edit!</button>
<button id="done_btn" onclick="done()">Done!</button>
</td>
</tr>
</table>
<script> document.getElementById("done_btn").disabled=true;</script>
</body>
</html>
I have used this plugin in the past and found it incredibly useful
http://vitalets.github.io/x-editable/

In jquery how to get the values of a particular row of a table that is selected using checkbox?

This is my jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Insert title here</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
</head>
<body>
<table id="one" style="border:1px solid red;">
<caption>Table 1</caption>
<thead>
<tr>
<th></th>
<th >ID</th>
<th> Name</th>
<th>System</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" /></td>
<td>12</td>
<td>Sam</td>
<td>FSS</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>87</td>
<td>Harry</td>
<td>MSS</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>23</td>
<td>Rita</td>
<td>MVV</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>65</td>
<td>Tom</td>
<td>RDD</td>
</tr>
</tbody>
</table>
<br><hr><br>
<button id="add">Add</button>
</body>
</html>
Here, when I click on add button I want to get all the values of the corresponding row that is checked in different variables namely id, name & system that should contain the checked values.
I want these values to be stored in a String (not map).
Could you please suggest me a jquery / js to achieve the folllowing
UPDATE
If I have a hidden field along with the checkbox how can I get its value?
For example
<td>
<input type="checkbox" />
<input type="hidden" value="secret" id="alertTyp" />
</td>
If you want the strings in <td>s, here is jQuery code for that:
var str = "";
$('#add').click(function(){
$('input:checkbox:checked').filter(function(){
str = $(this).closest('tr').text();
});
});
DEMO
Please see my fiddle for solution
[http://jsfiddle.net/a4WMc/]
http://jsfiddle.net/a4WMc/
Try this:
var stringresult = '';
$('#add').on('click', function () {
$('input:checked').each(function () {
$this = $(this);
var one = $this.parent().siblings('td').eq(0).text();
var two = $this.parent().siblings('td').eq(1).text();
var three = $this.parent().siblings('td').eq(2).text();
alert(one + ' ' + two + ' ' + three);
//or just
stringresult += $this.parent().siblings('td').text();
});
console.log(stringresult);
});
DEMO HERE
Try this:
$('#alertTyp').val()
You can iterate through all the rows...the question how performand would that be:
var str = '';
$('#one').find('tbody').find('tr').each(function()
{
if($(this).children().eq(0).attr('checked') == 'checked')
{
$(this).find('td').each(function()
{
str += $(this).text();
});
}
});
or something like that ...i don't have the time atm to test this sorry.
I would do something like this (untested code!!!) :
var myRow = $('input[type="checkbox"]:checked').parents('tr:first');
var result;
myRow.children('td').each(){
result += $(this).html() + "|";
}
this could work if there was only 1 checked checkbox... otherwise you need to cycle through all the checked checkboxes to get values...

"Add Row" logic not working as expected

It has taken me days to come up with the following, and now I'm realizing that it still doesn't work. My "add row" button isn't working properly. What am I missing?
<table>
<tr>
<th>field</th>
<th>comparison</th>
<th>value</th>
</tr>
<tr>
<td>
<select style="width:5em;" class="field">
<option>name</option>
<option>age</option>
<option>sex</option>
</select>
</td>
<td>
<select style="width:5em;" class = "comp">
<option>equals</option>
<option>starts with</option>
<option>not equal to</option>
</select>
</td>
<td><input type="text" class = 'value'></td>
<td><button id="add">Add row</button></td>
</tr>
</table>
$('#tableSearchMainAccount1 tr').each(function() {
var td = '';
// used to skip table header (if there is)
if ($(this).find("td:first").length > 0) {
$(this).find('option:selected').each(function() {
td = td + $(this).text() + ',';
});
td = td + $(this).find('input').val();
filt[ctr] = td;
ctr += 1;
}
});
//alert(filt); //alert output like name,equals,ann,age,equals,11
$('#add').live('click', function() {
var $lastTr = $('table tr:last');
console.log($lastTr);
$lastTr.clone().insertAfter($lastTr);
// Remove the button from the previous tr, otherwise each row will have it.
$('#add', $lastTr)
.replaceWith('<button class="remove_row">Remove row</button>');
});
$('.remove_row').live('click', function() {
$(this).closest('tr').remove();
});
From the discussion in the comments, it appears you have not referenced jQuery.
Add the following to your <head></head> section:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
There are many other CDNs that host jQuery for you, or you can download it yourself. All of these details can be found on http://jquery.com/download/.
So that your markup looks something like the following:
<!DOCTYPE html>
<html>
<head>
<title>My jQuery Project</title>
<script src="jquery-1.8.3.min.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<table>...</table>
</body>
</html>
Note that I also referenced another external file called "scripts.js". This is where you could place all of your JavaScript and jQuery logic.
$(document).ready(function(){
/* Wrapping your code with a document-ready
block will ensure that the DOM will be
ready before your code runs
*/
});
replace
<table>
with
<table id="tableSearchMainAccount1">
would be my starter for 10.

Categories

Resources