My question will ultimately be related to this site:
http://dbtest.net16.net/ethanol-01.html
EDIT: View unencrypted page source code here >>> http://dbtest.net16.net/ethanol-22.html
This is an HTML form with results calculated using JavaScript. My goal is to display a table of 2-6 columns and variable number of rows depending on user input (form would be modified). My problem is that I am not fully understanding how to get the table created in JavaScript after the user clicks the Calculate button. I have found some potential good answers but apparently don't fully understand it all. Running the following code is somewhat like what I want my output to display.
<html>
<!-- http://www.java2s.com/Tutorial/JavaScript/0220__Array/OutputarrayelementinaHTMLtableformat.htm -->
<head>
<title>Table of Numbers</title>
</head>
<body>
<h1>Table of Numbers</h1>
<table border="0">
<script language="javascript" type="text/javascript">
<!--
var myArray = new Array();
myArray[0] = 1;
myArray[1] = 2.218;
myArray[2] = 33;
myArray[3] = 114.94;
myArray[4] = 5;
myArray[5] = 33;
myArray[6] = 114.980;
myArray[7] = 5;
document.write("<tr><td style='width: 100px; color: red;'>Col Head 1</td>");
document.write("<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>");
document.write("<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>");
document.write("<tr><td style='width: 100px;'>---------------</td>");
document.write("<td style='width: 100px; text-align: right;'>---------------</td>");
document.write("<td style='width: 100px; text-align: right;'>---------------</td></tr>");
for (var i = 0; i < 8; i++) {
document.write("<tr><td style='width: 100px;'>Number " + i + " is:</td>");
myArray[i] = myArray[i].toFixed(3);
document.write("<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>");
document.write("<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>");
}
//-->
</script>
</table>
</body>
</html>
If I can get the test table to be created and populated with my test data using my actual javascript file, then I should then be able to figure the rest myself (I think).
Following are a couple of the best answers I could find so far:
http://jsfiddle.net/drewnoakes/YAXDZ/
The above link originated in stackoverflow but I can't seem to find the original post at this time.
http://www.java2s.com/Tutorial/JavaScript/0220__Array/OutputarrayelementinaHTMLtableformat.htm
Any help is appreciated. Simpler is better due to my limited experience.
The problem is that if you try to write a <table> or a <tr> or <td> tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.
Instead of writing your table line by line, concatenate your table into a variable and insert it once created:
<script language="javascript" type="text/javascript">
<!--
var myArray = new Array();
myArray[0] = 1;
myArray[1] = 2.218;
myArray[2] = 33;
myArray[3] = 114.94;
myArray[4] = 5;
myArray[5] = 33;
myArray[6] = 114.980;
myArray[7] = 5;
var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";
myTable+="<tr><td style='width: 100px; '>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td></tr>";
for (var i=0; i<8; i++) {
myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
myArray[i] = myArray[i].toFixed(3);
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
}
myTable+="</table>";
document.write( myTable);
//-->
</script>
If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:
<div id="tablePrint"> </div>
And in JS instead of document.write(myTable) use the following code:
document.getElementById('tablePrint').innerHTML = myTable;
In the html file there are three input boxes with userid,username,department respectively.
These inputboxes are used to get the input from the user.
The user can add any number of inputs to the page.
When clicking the button the script will enable the debugger mode.
In javascript, to enable the debugger mode, we have to add the following tag in the javascript.
/************************************************************************\
Tools->Internet Options-->Advanced-->uncheck
Disable script debugging(Internet Explorer)
Disable script debugging(Other)
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Dynamic Table</title>
<script language="javascript" type="text/javascript">
// <!CDATA[
function CmdAdd_onclick() {
var newTable,startTag,endTag;
//Creating a new table
startTag="<TABLE id='mainTable'><TBODY><TR><TD style=\"WIDTH: 120px\">User ID</TD>
<TD style=\"WIDTH: 120px\">User Name</TD><TD style=\"WIDTH: 120px\">Department</TD></TR>"
endTag="</TBODY></TABLE>"
newTable=startTag;
var trContents;
//Get the row contents
trContents=document.body.getElementsByTagName('TR');
if(trContents.length>1)
{
for(i=1;i<trContents.length;i++)
{
if(trContents(i).innerHTML)
{
// Add previous rows
newTable+="<TR>";
newTable+=trContents(i).innerHTML;
newTable+="</TR>";
}
}
}
//Add the Latest row
newTable+="<TR><TD style=\"WIDTH: 120px\" >" +
document.getElementById('userid').value +"</TD>";
newTable+="<TD style=\"WIDTH: 120px\" >" +
document.getElementById('username').value +"</TD>";
newTable+="<TD style=\"WIDTH: 120px\" >" +
document.getElementById('department').value +"</TD><TR>";
newTable+=endTag;
//Update the Previous Table With New Table.
document.getElementById('tableDiv').innerHTML=newTable;
}
// ]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<label>UserID</label>
<input id="userid" type="text" /><br />
<label>UserName</label>
<input id="username" type="text" /><br />
<label>Department</label>
<input id="department" type="text" />
<center>
<input id="CmdAdd" type="button" value="Add" onclick="return CmdAdd_onclick()" />
</center>
</div>
<div id="tableDiv" style="text-align:center" >
<table id="mainTable">
<tr style="width:120px " >
<td >User ID</td>
<td>User Name</td>
<td>Department</td>
</tr>
</table>
</div>
</form>
</body>
</html>
This beautiful code here creates a table with each td having array values. Not my code, but it helped me!
var rows = 6, cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}
Related
I have form . I wish to display values in table by clicking on add button
note: values will be stored in arrays
Use for loop
function loadTable() {
for (var i = 0; i < users.length; i++) {
"<tr id='row'>"
for (var j = 0; j < users[i].length; j++) {
$("#items_tbody").append(
"<td>" + items[i][j] +"</td>" +
)
+"</tr>"
console.log(items[i][j]);
}
}
}
table,
th,
td {
border: 1px solid black;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<!-- <form action="" method="get"> -->
<input type="number" name="id" id="id">
<input type="text" name="name" id="name">
<button type="button" id="submit">Add</button>
<table id="demo">
<tbody>
</tbody>
</table>
<!-- </form> -->
</body>
</html>
trying to get headers in tr and tbody data in tr seperatly but using for loop how can I do this
for (var j = 0; j < users[i].length; j++) {
$("#items_tbody").append(
"<td>" + items[i][j] +"</td>" +)
What this does is not create a DOM element. Just a string.
Here's what you need to do:
Create a element
const tdElement = document.createElement("td");
Add text content of items[i][j] to the newly created element
tdElement.textContent = items[i][j]
You can also add classes to the HTML element created using the classlist.add method
Now you need to append the element to the parent node like you already did using the appendChild method.
Here's the MDN guide. Please go through it for a clearer understanding
MDN docs
I made this simple website that adds and removes rows from a table. I have a two problems.The first one is whenever i add elements and them start deleting them my css style for my table is gone. Any idea how to fix it ? For example if i add 5rows and try to delete two of them then my style for all rows is gone. The second problem is how can i implement a function counter that will change the number of elements in the table and will keep track of them whenever someone removes or add new element. Here is my code:
var title = document.getElementById("title");
var author = document.getElementById("author");
var output = document.getElementById("output");
function addToTable() {
var radio = document.getElementsByName("content");
var radio_selected;
for (var a = 0; a < radio.length; a++) {
if (radio[a].checked) {
radio_selected =
radio[a].value;
}
}
output.innerHTML += "<tr>" + "<td>" + title.value + "</td>" +
"<td>" + author.value + "</td>" +
"<td>" + radio_selected + "</td>" +
"<td>" + "<input type='button' onclick='post(this);' id='post' value='Post'>" +
"<input type='button' onclick='remove(this);' id='remove'value='Remove'>" + "</td>" + "</tr>"
}
function counter() {
var counter = document.getElementById("counterForElements");
counter.innerHTML += 1;
}
function remove(btn) {
var row = btn.parentNode.parentNode;
var removed = document.getElementById("removed");
row.parentNode.removeChild(row);
}
function post(btn) {
var row = btn.parentNode;
row.parentNode.style.backgroundColor = "Green";
btn.setAttribute("disabled", "true");
btn.parentNode.lastElementChild.setAttribute("disabled", "true");
}
label {
width: 100px;
display: inline-block;
}
table,
th,
td,
tr,
td {
border: 1px solid black;
border-collapse: collapse;
}
table td {
text-align: center;
}
<!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></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
<div>
<label for="content" id="contentlabel">Content type</label>
<input type="radio" name="content" value="Free" class="content">Free
<input type="radio" name="content" value="Paid" class="content">Paid
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable(); counter();">
</div>
<div>
<h1>Number of elements<span id="counterForElements">0</span></h1>
</div>
<div>
<table id="output">
<th style="width:40%;">Title</th>
<th style="width:40%;">Author</th>
<th style="width:10%;">Type</th>
<th style="width:10%;">Button</th>
</table>
</div>
<div>
<h1>Removed elements</h1>
<table id="removed">
</table>
</div>
</body>
</html>
I think I have found what cause the border issue in Firefox.
Your output is set to the <table>, but you used <th> without <thead> nor <th>.
I simply added those missing tags, then I set the output to a new <tbody> tag.
It seems to work fine now.
var title = document.getElementById("title");
var author = document.getElementById("author");
var output = document.getElementById("output");
function addToTable() {
var radio = document.getElementsByName("content");
var radio_selected;
for (var a = 0; a < radio.length; a++) {
if (radio[a].checked) {
radio_selected =
radio[a].value;
}
}
output.innerHTML += "<tr>" + "<td>" + title.value + "</td>" +
"<td>" + author.value + "</td>" +
"<td>" + radio_selected + "</td>" +
"<td>" + "<input type='button' onclick='post(this);' id='post' value='Post'>" +
"<input type='button' onclick='remove(this);' id='remove'value='Remove'>" + "</td>" + "</tr>"
}
function counter() {
var counter = document.getElementById("counterForElements");
counter.innerHTML += 1;
}
function remove(btn) {
var row = btn.parentNode.parentNode;
var removed = document.getElementById("removed");
row.parentNode.removeChild(row);
}
function post(btn) {
var row = btn.parentNode;
row.parentNode.style.backgroundColor = "Green";
btn.setAttribute("disabled", "true");
btn.parentNode.lastElementChild.setAttribute("disabled", "true");
}
label {
width: 100px;
display: inline-block;
}
table,
th,
td,
tr,
td {
border: 1px solid black;
border-collapse: collapse;
}
table td {
text-align: center;
}
<!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></title>
</head>
<body>
<div>
<div>
<label for="Title">Title</label>
<input type="text" id="title">
</div>
<div>
<label for="Author">Author</label>
<input type="text" id="author">
</div>
<div>
<label for="content" id="contentlabel">Content type</label>
<input type="radio" name="content" value="Free" class="content">Free
<input type="radio" name="content" value="Paid" class="content">Paid
</div>
</div>
<div>
<input type="button" value="Add" onclick="addToTable(); counter();">
</div>
<div>
<h1>Number of elements<span id="counterForElements">0</span></h1>
</div>
<div>
<table>
<thead>
<th style="width:40%;">Title</th>
<th style="width:40%;">Author</th>
<th style="width:10%;">Type</th>
<th style="width:10%;">Button</th>
</thead>
<tbody id="output">
</tbody>
</table>
</div>
<div>
<h1>Removed elements</h1>
<table id="removed">
</table>
</div>
</body>
</html>
Your counter() function is not properly treating the innerHTML property as an integer. Here is a fix:
function counter() {
var counter = document.getElementById("counterForElements");
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
Another way would be with a global variable:
let counter = 0;
function counter() {
var counter = document.getElementById("counterForElements");
counter.innerHTML = ++counter;
}
If you want to keep track of removals, you would need to do so in remove():
function remove(btn) {
// ... existing code goes here
counter.innerHTML = parseInt(counter.innerHTML) + 1;
// or:
counter.innerHTML = --counter;
}
Another way would be to count the number of <tr> elements in the table and store that in counter.innerHTML every time you add or remove a row.
I want to find how many fields are there of type 'text' within the cell no. 3 of every each and every row.I want to save this in an array and want to pass it to my aspx.cs page in Asp.NET C#. I am able to get the number of text box within a page but i want them to count as per the raw and cell number.
I am generating this table dynamically.I want to get the number of text boxes within cell for each row
Scenario : I am having a scenario in which I want to generate a test report for a candidate. user will enter report name and when he clicks on the plus button, it will generate a dynamic row (that contains two text boxes) for the subject information. Within the dynamically generated raw one more button is there to generate the sub category of the subject. All the subject and sub categories i wan to insert in a same table but, subject id will be the parent id of the sub-subjects. I want them to retrieve in a parent-child form. please have a look on the screen shot attached.
<head id="Head1" runat="server">
<title></title>
<style type="text/css">
.TemplateTable
{
width: 80%;
margin-left: 3%;
border: 2px solid #a7a8a7;
margin-top: 30px;
padding-left: 35px;
font-size: 15px;
font-style: initial;
font-weight: bold;
color: #a7a8a7;
padding-top: 3px;
padding-bottom: 3px;
}
.TemplateTable tr td div
{
float: left;
padding-right: 10px;
font-size: 16px;
height: 22px;
}
.TemplateTable tr td div a
{
color: Blue;
}
.custom-tablePopup
{
font-family: Arial, Helvetica, sans-serif;
font-size: 13px;
margin: 10px 0 0 0;
padding: 0;
border-right: 1px solid #bebebe;
border-top: 1px solid #bebebe;
border-bottom: 1px solid #bebebe;
}
.custom-tablePopup th
{
background: #ff5c00 !important;
text-align: left;
border-left: 1px solid #bebebe;
border-bottom: 1px solid #bebebe;
padding: 5px 8px;
color: #fff;
}
.custom-tablePopup td
{
border-left: 1px solid #bebebe;
padding: 4px 8px;
}
.custom-tablePopup tr:nth-child(even)
{
background: #f8f8f8;
}
</style>
<script type="text/javascript">
var count = "1";
function addRow(in_tbl_name) {
var tbody = document.getElementById(in_tbl_name).getElementsByTagName("TBODY")[0];
// create row
var row = document.createElement("TR");
// create table cell 2
var td1 = document.createElement("TD")
var strHtml2 = "<input type=\"text\" name=\"SName\" size=\"20\" maxlength=\"30\" />";
td1.innerHTML = strHtml2.replace(/!count!/g, count);
// create table cell 3
var td2 = document.createElement("TD")
var strHtml3 = "<input type=\"text\" name=\"SScore\" size=\"10\" />";
td2.innerHTML = strHtml3.replace(/!count!/g, count);
// create table cell 4
var td3 = document.createElement("TD")
var strHtml4 = "<img src=\"../Images/cancel.jpg\" onclick=\"delRow()\" style=\"width: 22px; cursor:pointer;\" />";
td3.innerHTML = strHtml4.replace(/!count!/g, count);
// create table cell 4
var td4 = document.createElement("TD")
var strHtml5 = "<img src=\"../Images/Plus.jpg\" onclick=\"AddSubRow()\" style=\"width: 22px; cursor:pointer;\" />";
td4.innerHTML = strHtml5.replace(/!count!/g, count);
// append data to row
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
count = parseInt(count) + 1;
// add to count variable
// append row to table
tbody.appendChild(row);
}
function delRow() {
var current = window.event.srcElement;
//here we will delete the line
while ((current = current.parentElement) && current.tagName != "TR");
current.parentElement.removeChild(current);
}
function AddSubRow() {
var current = window.event.srcElement;
var row1 = document.createElement("TR");
// create table cell 1
var td1 = document.createElement("TD")
var strHtml2 = "<input type=\"text\" name=\"SubjectName\" size=\"20\" />";
td1.innerHTML = strHtml2.replace(/!count!/g, count);
// create table cell 2
var td2 = document.createElement("TD")
var strHtml3 = "<input type=\"text\" name=\"SubjectScore\" size=\"10\" />";
td2.innerHTML = strHtml3.replace(/!count!/g, count);
// create table cell 2
var td3 = document.createElement("TD")
var strHtml4 = "<img src=\"../Images/cancel.jpg\" onclick=\"delRow()\" style=\"width: 22px; cursor:pointer;\" />";
td3.innerHTML = strHtml4.replace(/!count!/g, count);
row1.appendChild(td1);
row1.appendChild(td2);
row1.appendChild(td3);
//here we will delete the line
//while ((current = current.parentElement) && current.tagName != "TR");
current.parentElement.appendChild(row1);
}
function Calculate() {
// var oTable = document.getElementById('tblPets');
var marks = [];
var table = document.getElementById("tblPets");
var column_count = table.rows[1].cells.length;
var rowLength = table.rows.length;
alert(document.querySelectorAll('input[type="text"]').length);
}
</script>
</head>
<body>
<form id="form1" runat="server" method="post">
<div id="dvReport" runat="server">
<table class="TemplateTable" runat="server" >
<tr>
<td>
Report Name <asp:TextBox ID="txtreportName" runat="server" Width="500px"></asp:TextBox>
</td>
<td style="float: right;">
<div>
<img id="Img1" src="~/Images/Plus.jpg" width="20" runat="server" /></div>
<div>
<a title="Add Subject" style="cursor: pointer;font-family:Arial;color:navy" onclick="addRow('tblPets')">Add Subject</a>
</div>
</td>
</tr>
</table>
</div>
<div style="margin-left: 3%;" id="dvSubject" runat="server">
<table id="tblPets" class="custom-tablePopup" runat="server">
<tr>
<th>Subject Name</th>
<th>Subject Score</th>
<th></th>
<th></th>
</tr>
<tr>
<td><input type="text" name="SName" size="20" /></td>
<td><input type="text" name="SScore" size="10" /></td>
<td><img src="../Images/Delete.png" onclick="delRow()" style="width: 22px; cursor: pointer;" /></td>
<td><img src="../Images/Plus.jpg" onclick="AddSubRow()" style="width: 22px; cursor: pointer;" /></td>
</tr>
</table>
</div>
<div>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="Calculate()" OnClick="btnSave_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</div>
<div>
<asp:Label ID="lblDisplay" runat="server"></asp:Label>
<asp:Literal ID="lit" runat="server"></asp:Literal>
</div>
</form>
</body>
you can add a specific class to the wanted elements, use javascript QuerySelector
document.querySelectorAll('.specific-class').length;
I have been given a task to make 2 HTML pages, one with form where the user enter his/her contact information and another where the user's information are viewed in a table.
I just need to use these languages only (JavaScript, jquery, HTML, CSS ,bootstrap); no use of PHP/JSP, only client-side language
and no database should be used. Up until now I have done this much.
$(function()
{
$('#form').validate(
{
rules:
{
email:
{required:true,
email:true
},
gender:
{required:true
},
cont:{
required:true,
number:true}
}
})
});
function onsumit(){
localStorage.setItem("input0",1);
var ip=document.getElementById("name");
localStorage.setItem("input1", ip.value);
var ip2=document.getElementById("email");
localStorage.setItem("input2", ip2.value);
var ip3=document.getElementById("cont");
localStorage.setItem("input3", ip3.value);
var ip4=document.getElementById("gender");
localStorage.setItem("input4", ip4.value);
var ip5=document.getElementById("comment");
localStorage.setItem("input5", ip5.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"
type="text/javascript"></script>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a> CONTACT FORM</a>
<form class="table-responsive" id="form" name="form" action="next.html" method="get" onsubmit="onsumit()" >
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name"required>*<p id="p1"></p></td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont"required>*<p id="p2"></p></td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email"required>*<p id="p3"></p></td>
</tr>
<tr>
<td>Gender:</td>
<td><select id="gender" name="gender" required>
<option value="" >SELECT</option>
<option value="male">MALE</option>
<option value="female">FEMALE</option>
</select>*<p id="p4"></p></td>
</tr>
<tr>
<td>comments:</td>
<td> <textarea class="form-control" rows="5" id="comment" maxlength="100"></textarea>
</td>
</tr>
</table>
<label><input id="submit" type="submit" value="SUBMIT"></label>
</form>
</div>
now this is the second html page.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
body {
font: 20px Montserrat, sans-serif;
line-height: 1.8;
color: black;
}
p {font-size: 16px;}
.margin {margin-bottom: 45px;}
.bg-1 {
background-color: #1abc9c; /* Green */
color: #ffffff;
}
.bg-2 {
background-color: #474e5d; /* Dark Blue */
color: #ffffff;
}
.bg-3 {
background-color: #ffffff; /* White */
color: #555555;
}
.bg-4 {
background-color: #2f2f2f; /* Black Gray */
color: #fff;
}
.container-fluid {
padding-top: 70px;
padding-bottom: 70px;
}
.navbar {
padding-top: 15px;
padding-bottom: 15px;
border: 0;
border-radius: 0;
margin-bottom: 0;
font-size: 12px;
letter-spacing: 5px;
}
.navbar-nav li a:hover {
color: #1abc9c !important;
}
#divmid {
margin:20px;
padding:20px;
border:3px solid red;
}
table{
text-align:left ;
}
th, td {
padding: 20px;
text-align:left;
}
textarea{
max-height:300px;
resize:none;
}
#div1{
text-align:center;
}
#tab2 {
text-align:left ;
border:2px solid red;
margin-left:auto;
margin-top:40px;
margin-bottom:200px;
}
#pick{
padding:100px;
}
<style>
table, td,th{
border: 1px solid black;
}
</style>
<body onload="load()">
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>S No.</th>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
<th>GENDER</th>
<th>COMMENTS</th>
<th>EDIT</th>
</tr>
</table>
</div>
</body>
The problem is I need to create a row in second page each time a user input with the new values in the form, but what in have done, it only creating one row and always updating it with the new values. Though I have used Local storage but still I am stuck here.
The problem is in the line 6 of your code. The parameter 1 passed to the insertRow function instantiates the variable row with the first row of your table. This way, every time you use insertCell in the row variable it updates the value on this first row. I think switching to rowCount + 1 will do the job.
function load(){
var table = document.getElementById("tab2");
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1);
var row = table.insertRow(rowCount + 1);
for(var i=0; i < colCount; i++) {
var text = localStorage.getItem("input"+i);
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type='button' value='X' id='work' onclick='removeLine(this)'/><INPUT type='button' value='&' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
}
}
function removeLine(lineItem) {
var row = lineItem.parentNode.parentNode;
row.parentNode.removeChild(row);
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
}
take a look at this code. I think it should be what you are looking for.
Everytime the form is submitted, I first get the value of the local storage and add the new entry as JSON.
On the other page, I get the local storage, transform the value to get an object from the JSON string and use that object to show the informations inside the table.
Hope this help!
First Page :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function onsumit() {
if (typeof(Storage) !== "undefined") {
// Exemple of str : {'d' : [{'name':'Mister A','cont':'1',email':'MisterA#test.com'},{'name':'Mister B','cont':'1','email':'MisterB#test.com'}]}
var str = localStorage.getItem("contactinformation");
var contactModel;
if (str !== '') {
contactModel = JSON.parse(str);
} else {
contactModel = {
d : []
};
}
contactModel.d[contactModel.d.length] = {
name:$('#name').val(),
cont:$('#cont').val(),
email:$('#email').val()
}
localStorage.setItem("contactinformation",JSON.stringify(contactModel));
return true;
} else {
// Sorry! No Web Storage support..
return false;
}
}
</script>
</head>
<body>
<div class="divmid text-center" id="divmid" >
<p id="head"></p>
<a>CONTACT FORM</a>
<form id="form" name="form" action="next.html" method="get" onsubmit="return onsumit();">
<table>
<tr>
<td>NAME:</td>
<td><input type="text" name="name" id="name">*</td>
</tr>
<tr>
<td>Contcat no:</td>
<td><input type="text" size="10" name="cont" id="cont">*</td>
</tr>
<tr>
<td>EMAIL:</td>
<td><input type="text" name="email" id="email">*</td>
</tr>
</table>
<input id="submit" type="submit" value="SUBMIT">
</form>
</div>
</body>
</html>
Second Page :
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
table, td,th{
border: 1px solid black;
}
</style>
</head>
<body>
<div id="div1">
<span id="div2">CONTACT LIST</span>
<table id="tab2">
<tr>
<th>NAME</th>
<th>CONTACT</th>
<th>EMAIL</th>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
if (typeof(Storage) !== "undefined") {
var str = localStorage.getItem("contactinformation");
var info = JSON.parse(str);
if (typeof(info.d) !== "undefined") {
for (var x=0;x<info.d.length;x++) {
$('#tab2').append('<tr><td>' + info.d[x].name + '</td><td>' + info.d[x].cont + '</td><td>' + info.d[x].email + '</td></tr>');
}
}
}
});
</script>
</body>
</html>
I am adding an element to an html page using javascript when a button is clicked and making an onclick attribute on this button to alert something as a test to make it execute something but it is not alerting anything when this added button is clicked. Here is the codes.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
</style>
</head>
<body>
<div style="display:inline-flex;">
<input id="inptext" type="text" placeholder="Your name..."></input>
<input id="inpadress" style="margin-left: 10px;" id="inptext" type="text" placeholder="Your email..."></input>
<button onclick="myFunction()"style="margin-left: 10px;" id="box">Add</button>
</div>
<br>
<div style="display: inline-flex">
<table id="tablename" style="width:80%; margin-top:15px;">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</table>
<div id="buttons" style="float:right;width: 300px; margin-top:50px;">
</div>
</div>
<script>
var z = 1;
function myFunction() {
var x = document.getElementById("inptext").value;
var y = document.getElementById("inpadress").value;
document.getElementById("tablename").innerHTML = document.getElementById("tablename").innerHTML + '<tr><td>' + x + '</td><td>' + y + '</td></tr>';
document.getElementById("buttons").innerHTML = document.getElementById("buttons").innerHTML + '<button onclick="myFunctionedit()" style="margin-left:8px" class="edit" id="vda' + z + '">Edit</button><button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button><button style="margin-left:8px" class="update" id="cvda' + z + '">Update</button></div><div id="zzza' + z + '" style="height:10px"></div>';
document.getElementById('cvda'+z).style.visibility = 'hidden';
z = z+1;
}
</script>
</body>
</html>
Inside the alert you are using double quotes:
<button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">
Try changing it to single quotes:
<button onclick="window.alert(\'sometext\');" style="margin-left:4px" class="deleteit" id="a' + z + '">
<button onclick="window.alert("sometext");" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button>
makes for invalid html.
Try
<button onclick="window.alert(\'sometext\');" style="margin-left:4px" class="deleteit" id="a' + z + '">Remove</button>
On top of that, the float: right; in #buttons is making the buttons unclickable. You can either remove that float or give it a z-index.
Working JSFiddle: https://jsfiddle.net/L8ymqLwh/ (with float: right; removed)