print javascript results into div tag - javascript

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>

Related

JavaScript won't include tr- and td-tags in string

i am trying to insert a <tr> and a <td> into a table using javascript.
I have a fairly simple javascript-code that prints a string every time I click a button. It's being printed into a <table>, but javascript ignores the <tr> and <td>tags.
How do I make Javascript include <tr> and <td> tags?
I gave already tried escaping the string in various ways.
code used:
<script>
function MoreCameras() {
document.getElementById("AddCamera").innerHTML += "<tr><td><input type='text' name='SSIDSetup[]' class='form-control' placeholder='Camera SSID'></td><td><input type='text' name='NameSetup[]' class='form-control' placeholder='Camera Name'></td><td><input type='password' name='PasswordSetup[]' class='form-control' placeholder='Camera Password'></td><td><input type='checkbox' name='EnabledSetup[]'/></td></tr>";
}
</script>
<button onclick="MoreCameras()">Try it</button>
<table>
<div id="AddCamera">
</div>
</table>
screenshot for clarification
It's generally not a good idea to use inline event handlers.
You can't add table rows to a div. Here's a snippet using event delegation and adding the innerHTML to the table. It may be more approriate to create a row using DOM-scripting, cf MDN. Added a function for that to the snippet.
It is not uncommon to see innerHTML used to insert text into a web
page. There is potential for this to become an attack vector on a
site, creating a potential security risk.
document.addEventListener("click", MoreCameras);
function MoreCameras(evt) {
if (evt.target.id === "ih") {
document.querySelector("#AddCamera").innerHTML += getRowHtml();
}
if (evt.target.id === "ds") {
document.querySelector("#AddCamera").appendChild(createRow());
}
}
function createRow() {
const row = document.createElement("tr");
const cells = [...Array(4)].map(td => document.createElement("td"));
const inputs = [...Array(4)].map(input => document.createElement("input"));
inputs[0].type = "text";
inputs[0].name = "SSIDSetup[]";
inputs[0].classList.add("form-control");
inputs[0].setAttribute("placeholder", "Camera SSID");
inputs[1].type = "text";
inputs[1].name = "NameSetup[]";
inputs[1].classList.add("form-control");
inputs[1].setAttribute("placeholder", "Camera Name");
inputs[2].type = "password";
inputs[2].name = "PasswordSetup[]";
inputs[2].classList.add("form-control");
inputs[2].setAttribute("placeholder", "Camera Password");
inputs[3].type = "checkbox";
inputs[3].name = "EnabledSetup[]";
cells.forEach((cell, i) => {
cell.appendChild(inputs[i]);
row.appendChild(cell);
});
return row;
}
function getRowHtml() {
return `
<tr>
<td>
<input
type="text"
name="SSIDSetup[]"
class="form-control"
placeholder="Camera SSID">
</td>
<td>
<input
type="text"
name="NameSetup[]
class="form-control"
placeholder="Camera Name">
</td>
<td>
<input
type="password"
name="PasswordSetup[]"
class="form-control"
placeholder="Camera Password">
</td>
<td>
<input
type="checkbox"
name="EnabledSetup[]">
</td>
</tr>`;
}
<button id="ih">Try it (innerHTML)</button>
<button id="ds">Try it (DOM scripting)</button>
<table>
<tbody id="AddCamera"></tbody>
</tabe>
You are inserting cell based elements into a div, this is not valid html.
add a tbody thead and add the id you insert into to the tbody
Just remove div and put id="AddCamera" on table. You where inserting td tr in wrong way.
EDIT:
actually add tbody with that id, that will give you right HTML syntax
<tbody id="AddCamera">
<script>
function MoreCameras() {
document.getElementById("AddCamera").innerHTML += "<tr><td><input type='text' name='SSIDSetup[]' class='form-control' placeholder='Camera SSID'></td><td><input type='text' name='NameSetup[]' class='form-control' placeholder='Camera Name'></td><td><input type='password' name='PasswordSetup[]' class='form-control' placeholder='Camera Password'></td><td><input type='checkbox' name='EnabledSetup[]'/></td></tr>";
}
</script>
<button onclick="MoreCameras()">Try it</button>
<table>
<tbody id="AddCamera">
</tbody>
</table>

how to use html table "td" element in javascript in different cases?

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.

Can't add data to table with plain 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)
}
<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.

HTML Table - Iterate over row and sum the fields

I have then following table:
<table style="width:100%" id="testTable">
<tr>
<th>length per</th>
<th>width per</th>
<th>length</th>
<th>width</th>
<th>total</th>
</tr>
<tr align='right'>
<td>
<input type="text" name="length-per-input">
</td>
<td>
<input type="text" name="width-per-input">
</td>
<td>
<input type="text" name="length-total-input">
</td>
<td>
<input type="text" name="width-total-input">
</td>
<td>
<input type="text" name="total-output" disabled="disabled">
</td>
</tr>
<tr align='right'>
<td>
<input type="text" name="length-per-input">
</td>
<td>
<input type="text" name="width-per-input">
</td>
<td>
<input type="text" name="length-total-input">
</td>
<td>
<input type="text" name="width-total-input">
</td>
<td>
<input type="text" name="total-output" disabled="disabled">
</td>
</tr>
</table>
<input type=button value='+' onclick="addRow()" />
<input type=button value='Calculate' onclick="Calculate()" />
I also have the javascript which adds the value and puts it in total:
<script>
function Calculate() {
var lengthPerInput = $("input[name='length-per-input']").val();
var widthPerInput = $("input[name='width-per-input']").val();
var lengthTotal = $("input[name='length-total-input']").val();
var widthTotal = $("input[name='width-total-input']").val();
var total = (lengthTotal/lengthPerInput) + (widthTotal/widthPerInput);
$("input[name='total-output']").val(total);
}
</script>
The aim here is to have it iterate over the two rows, then add each one separately.
I know how to get each row by using:
$('#testTable tr').each(function(){
console.log(this);
$(this).find('length-per-input').each(function(){
console.log(this);
})
})
But using the row (accessed via "this") I don't know how to get the correct cells, get their value, then perform the calculate on that row for the total.
Any advice on this please? Thank you!
function Calculate(tr_row) {
var lengthPerInput = tr_row.find("input[name='length-per-input']").val();
var widthPerInput = tr_row.find("input[name='width-per-input']").val();
var lengthTotal = tr_row.find("input[name='length-total-input']").val();
var widthTotal = tr_row.find("input[name='width-total-input']").val();
var total = (lengthTotal/lengthPerInput) + (widthTotal/widthPerInput);
tr_row.find("input[name='total-output']").val(total);
}
For every row you call function to summ the values
To the function you pass the row, then it can collect values on that row
$('#testTable tr').each(function(){
Calculate($(this))
})
You can use each() function to iterate through table and use find() function to find cell values.
function Calculate() {
$('#testTable tr').each(function() {
var lengthPerInput = $(this).find("input[name='length-per-input']").val();
var widthPerInput = $(this).find("input[name='width-per-input']").val();
var lengthTotal = $(this).find("input[name='length-total-input']").val();
var widthTotal = $(this).find("input[name='width-total-input']").val();
var total = (lengthTotal/lengthPerInput) + (widthTotal/widthPerInput);
$(this).find("input[name='total-output']").val(total);
});
}
Working Plunker
How to get a table cell value using jQuery?

How to add and remove lines from a html table

I have the table:
<table id="form_Dependentes" width="100%" cellpadding="0" cellspacing="0" class="form">
<tr>
<th colspan="4" valign="middle" scope="col">Dependentes</th>
</tr>
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_01" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_01" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_01" maxlength="10" /></td>
</tr>
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_02" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_02" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_02" maxlength="10" /></td>
</tr>
... etc.
</table>
This table is formatted to be printed and used online. Online, I wish to put buttons to add and remove those lines with input tags above the header. Is not complicate to format the html, but I was thinking about removing and adding tr lines using xml javascript capabilities, but don't know exactly how...
Edit: I don't get what so wrong with this question that is getting negative. Whatever... I'm working in this code:
var cadFormTableRow;
var cadFormTable;
function cadFormAtivar(){
document.getElementById("form_FotoUpload").innerHTML = 'Foto (máximo 1MB): <input name="foto" type="file" accept="image/*;capture=camera">';
document.getElementById("form_Assinatura").innerHTML = '';
document.getElementById("form_Dados").innerHTML = 'Dependentes: <button type="button" onclick="cadFormDep(1);"> + </button> <button type="button" onclick="cadFormDep(-1);"> - </button><br /><button type="button" onclick="cadFormTestar();">Enviar</button>';
cadFormTable = document.getElementById("form_Dependentes");
var nr = cadFormTable.rows.length;
cadFormTableRow = cadFormTable.rows[1];
console.log("Rows: "+nr);
//console.log("Row: "+cadFormTableRow.outerHTML);
for(i=0; i<nr-1; i++){
cadFormTable.deleteRow(1);
}
}
function cadFormDep(a){
if(a>0){
cadFormTable.appendChild(cadFormTableRow);
} else {
var nr = cadFormTable.rows.length;
cadFormTable.deleteRow(nr-1);
}
}
The problem seams to be appendChild is not good, I should go deep in HTMLTableElement, I guess, that's what I like to choose the better approach first... If I could make it work, I'll answer myself, I don't mind you don't like it, it's a free world, right?
It seams HTMLTableElement is the best approach for inserting and deleting rows. HTMLTableElement.insertRow creates a row linked with the original object. Here is the same code with HTMLTableElement corrections needed:
var cadFormTableRow;
var cadFormTable;
function cadFormAtivar(){
document.getElementById("form_FotoUpload").innerHTML = 'Foto (máximo 1MB): <input name="foto" type="file" accept="image/*;capture=camera">';
document.getElementById("form_Assinatura").innerHTML = '';
document.getElementById("form_Dados").innerHTML = 'Dependentes: <button type="button" onclick="cadFormDep(1);"> + </button> <button type="button" onclick="cadFormDep(-1);"> - </button><br /><button type="button" onclick="cadFormTestar();">Enviar</button>';
cadFormTable = document.getElementById("form_Dependentes");
var nr = cadFormTable.rows.length;
cadFormTableRow = cadFormTable.rows[1];
for(i=0; i<nr-1; i++){
cadFormTable.deleteRow(1);
}
}
function cadFormDep(a){
if(a>0){
var row = cadFormTable.insertRow(-1);
var html = cadFormTableRow.innerHTML.replace(/{n}/g, String(cadFormTable.rows.length-1));
row.innerHTML = html;
console.log("Row: "+html);
} else {
var nr = cadFormTable.rows.length;
cadFormTable.deleteRow(nr-1);
}
}
I think working with the cells and inputs as string were easier in this case - I'd pick a sample (as below) and add a number replacing {n} by a numbering:
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_{n}" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_{n}" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_{n}" maxlength="10" /></td>
</tr>
This way, every the information will have an unique name.

Categories