This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
The script i made loops and creates a table(s) based on user input, if super=2 then there should be 2 tables outputed with different numbers in the tables its working pretty well, except that it is printing the first table as it should, then when it does the second one, it reprints the fist one also.. any ideas?
code:
<html>
<head>
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
var y = 1;
for( var i = 1; i <= num_super; i++){
var theader = '<div style="margin:0 auto;"><table border="1" style="border:1px solid black; float:left;">\n';
for(u = 1; u <= num_rows; u++){
tbody += '<tr>';
for( var j = 1; j <= colStart; j++)
{
tbody += '<td style="width:80px; height:70px;">';
tbody += '<sub style="float:right; position:relative; top:24px; z-index:11; ">' + y + '</sub>';
tbody += '</td>';
y++;
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML += theader + tbody + tfooter;
}
}
</script>
</head>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
what i should look like:
what it is looking like:
Like the comment says - you clear tBody
var tbody = '';
before the loop , but that only happens once . Since it is delclared outside the loop , and never reset to '' , the contents of the first table are still in there for the second loop , try
for( var i = 1; i <= num_super; i++){
var tbody = '';
//...
Here you are
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
var y = 1;
for( var i = 1; i <= num_super; i++){
var theader = '<div style="margin:0 auto;"><table border="1" style="border:1px solid black; float:left;">\n';
tbody = '';
for(u = 1; u <= num_rows; u++){
tbody += '<tr>';
for( var j = 1; j <= colStart; j++)
{
tbody += '<td style="width:80px; height:70px;">';
tbody += '<sub style="float:right; position:relative; top:24px; z-index:11; ">' + y + '</sub>';
tbody += '</td>';
y++;
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML += theader + tbody + tfooter;
}
}
</script>
</head>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
added var tbody = '';
Related
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 have a form within a table with Title and description columns and the rows can be added dynamically by a button. I need to access and save the input values in text boxes created by javascript function when saving the form by save button. the input values are later saved on local storage. The saved values are used to repopulate the form in case of unsuccessful validation.
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title' + x + '" /></td>' +
'<td> <input type="text" id="description' + x + '" /></td></tr>';
}
function save_data() {
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows; i++) {
for (var j = 0; j < 2; j++) {
var title = document.getElementById('title' + i).value;
var desc = document.getElementById('description' + i).value;
var temp = {
title: title,
description: desc
};
data.push(temp);
}
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
did you mean something like this?
$(document).ready(()=>{
$('#container').append('<input id="addedTxt" type="text" />');
$('#addedTxt').val('Test');
$('#saveBtn').on('click', ()=>{
alert($('#addedTxt').val());
});
});
<div id="container">
</div>
<input id="saveBtn" type="button" value="save" />
(using jquery)
https://jsfiddle.net/u6vnxwzc/1/#&togetherjs=rQ2b5IsJQ1
or where is the problem?
In your code why you use the second For loop? I think it is not necessary.
find the working code snippet
https://s.codepen.io/mastersmind/debug/VNyKrY/DqADdKoRXEjA
function add_text_input() {
var table = document.getElementById('mytable');
var x = table.rows.length;
table.insertRow(-1).innerHTML = '<tr>' +
'<td> <input type="text" id="title'+x+'" /></td>'+
'<td> <input type="text" id="description'+x+'" /></td></tr>';
}
function save_data(){
var table = document.getElementById('mytable');
var tableRows = table.rows.length;
var data = [];
for (var i = 1; i <= tableRows-1; i++) {
var title = document.getElementById('title'+ i).value;
var desc = document.getElementById('description'+ i).value;
var temp = {title: title, description: desc};
data.push(temp);
}
window.localStorage.setItem('Table1', JSON.stringify(data));
}
loadData = function(){
let data = JSON.parse(window.localStorage.getItem('Table1'));
for(i=0; i<data.length;i++){
add_text_input();
document.getElementById('title'+ (i+1)).value = data[i].title;
document.getElementById('description'+ (i+1)).value = data[i].description;
}
}
loadData();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<table id="mytable">
<tr>
<td> Title </td>
<td> Description </td>
</tr>
</table>
<input type="button" onclick="add_text_input()" value="add row">
<input type="button" onclick="save_data()" value="save">
</form>
</body>
</html>
the problem here is i don't need input field required when i remove required the table still empty and another problem when i enter (not valid character)
also the table data will be deleted
i need the input field not required and when click add it adds a new row
var myInput = document.getElementById("myInput")
myTable = document.getElementById("myTable")
i = 1
num = 1
tabledata = myTable.innerHTML;
function arr() {
if(myInput.value!=""){
if(/^[a-z]+$/i.test(myInput.value)){
if (num % 2 == 0) {
myTable.innerHTML = myTable.innerHTML + '<tr style="background:#ff8000"><td>' + i + '</td><td>' + myInput.value + "</td></tr>";
myInput.value = "";
i++;
} else {
myTable.innerHTML = myTable.innerHTML + '<tr style="background:#ffb366"><td>' + i + '</td><td>' + myInput.value + "</td></tr>";
myInput.value = "";
i++;
}
num++;
}
else {
alert("Please Enter A Valid Charceter");
}
}else{
alert("This Field Is Reqiured Please Enter Your Name")
}};
function res() {
myTable.innerHTML = "<tr> <th>Id</th> <th>Name</th> </tr>";
i = 1;
num = 1;
}
<h1>Enter Your Name</h1>
<form>
<input type="text" id="myInput" required/>
<button onclick="arr()">Add</button>
</form>
<table id="myTable">
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</table>
<button onclick ="res()">Reset</button>
I didn't fully understand what you need, but I see here a little bit flaw:
When you click the "Add" button, the form is submitting, so you need to break this.
Try it:
<style>
#myTable tr {
background: #FF8000
}
#myTable tr:nth-child(odd){
background: #FFB366
}
</style>
<h1>Enter Your Name</h1>
<form id="myForm">
<input type="text" id="myInput" required />
<input type="submit" />
</form>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody id="myTable"></tbody>
</table>
<button id="myButton">Reset</button>
<script>
(function(){
"use strict";
var
form = document.getElementById("myForm"),
input = document.getElementById("myInput"),
table = document.getElementById("myTable"),
reset = document.getElementById("myButton");
form.addEventListener("submit", add, true);
function add(event){
event.preventDefault();
if( /^[a-z]+$/i.test(myInput.value) )
table.innerHTML += '<tr><td>' + (table.children.length + 1) + '</td><td>' + input.value + '</td></tr>';
return input.value = '';
}
function reset(){
table.innerHTML = '';
}
})()
</script>
I want to make a site where a group of people have to add some data, later I will store them into a database.
I don't know the exact number of people and the exact number of rows so I made a function in JavaScript that generates a table when a button is pressed, and same with the rows.
I have some problems that I can't find the solution, that's why I ask here for help:
When I press the button "Add new Table" is like he enters on another page to load it. I tried to use tag and also but still the same.
When I press on "addRow" he put the id(number) 1 again, but I incremented the counter, again I don't know where is happend this.
When I add a new table and I try to add a row to it, he put the row to the first table, I was thinking that this is happend because all the tables have the same id, but why he don't add a row to all of them?
I want to add the row to that particular table where I press the button. My solution would be to add a particular id to every table.
I tried this:
var tableId = 1;
document.write('<div class="window_wrap"> <table class="window" id="idWindowTable' + tableId++ + '">' + table + '</table> </div>');
but I don't know how to increment the id in the addRow function:
var windowTab = document.getElementById("idWindowTable");
Here is my script:
<script>
var table = ''; //table from genTab
var rows = 1; //for genTab
var cols = 3; //for genTab
var rowCounter = 3; //starts from index 3 when add row on table
var nr = 1; // write the id at the number
var tableId = 1;
function genTab() {
table += '<tr> <th class="window_cells" colspan="3"><form class="window_form"><span>Cordonator: </span><input type="text" name="prof_name" placeholder="Prof. dr. Nume Prenume" required/><input type="email" name="prof_email" required/><input type="submit" value="Submit"/></form></th> </tr> <tr><td class="window_cells">Nr</td> <td class="window_cells" id="test">Tema</td> <td class="window_cells">Detalii</td> </tr>';
for(var r = 0; r < rows; r++)
{
table += '<tr>';
for(var c = 0; c < cols; c++)
{
if(c==0)
table += '<td class="window_cells">' + nr++ + '</td>';
else
table += '<td class="window_cells"> <textarea rows="4" cols="30"> </textarea> </td>';
}
table += '</tr> <tr> <th class="window_cells" colspan="3"> <form> <input type="button" value="Preview"/> <input type="submit" value="Submit row"/> <input type="button" value="Add new Table" onClick="genTab()"/> <input id="idRowButton" type="button" value="Add row" onClick="addRow()"/> </form> </th> </tr>';
}
document.write('<div class="window_wrap"> <table class="window" id="idWindowTable">' + table + '</table> </div>');
nr = 1;
table = '';
}
function addRow() {
var windowTab = document.getElementById("idWindowTable");
var roww = windowTab.insertRow(rowCounter++);
var cell1 = roww.insertCell(0);
var cell2 = roww.insertCell(1);
var cell3 = roww.insertCell(2);
cell1.innerHTML = nr++;
cell1.className = "window_cells";
cell2.innerHTML = "<textarea rows=\"4\" cols=\"30\"> </textarea>";
cell2.className = "window_cells";
cell3.innerHTML = "<textarea rows=\"4\" cols=\"30\"> </textarea>";
cell3.className = "window_cells";
}
genTab();
</script>
Here is a begin. Use innerHTML and remove the nr=1 in the genTab function
var table = ''; //table from genTab
var rows = 1; //for genTab
var cols = 3; //for genTab
var rowCounter = 3; //starts from index 3 when add row on table
var nr = 1; // write the id at the number
var tableId = 1;
function genTab() {
table += '<tr> <th class="window_cells" colspan="3"><form class="window_form"><span>Cordonator: </span><input type="text" name="prof_name" placeholder="Prof. dr. Nume Prenume" required/><input type="email" name="prof_email" placeholder="(email#info.uvt.ro)" required/><input type="submit" value="Submit"/></form></th> </tr> <tr><td class="window_cells">Nr</td> <td class="window_cells" id="test">Tema</td> <td class="window_cells">Detalii</td> </tr>';
for (var r = 0; r < rows; r++) {
table += '<tr>';
for (var c = 0; c < cols; c++) {
if (c == 0)
table += '<td class="window_cells">' + nr+++'</td>';
else
table += '<td class="window_cells"> <textarea rows="4" cols="30"> </textarea> </td>';
}
table += '</tr> <tr> <th class="window_cells" colspan="3"> <form> <input type="button" value="Preview"/> <input type="submit" value="Submit row"/> <input type="button" value="Add new Table" onClick="genTab()"/> <input id="idRowButton" type="button" value="Add row" onClick="addRow()"/> </form> </th> </tr>';
}
document.getElementById("content").innerHTML+='<div class="window_wrap"> <table class="window" id="idWindowTable">' + table + '</table> </div>';
table = '';
}
function addRow() {
var windowTab = document.getElementById("idWindowTable");
var roww = windowTab.insertRow(rowCounter++);
var cell1 = roww.insertCell(0);
var cell2 = roww.insertCell(1);
var cell3 = roww.insertCell(2);
cell1.innerHTML = nr++;
cell1.className = "window_cells";
cell2.innerHTML = "<textarea rows=\"4\" cols=\"30\"> </textarea>";
cell2.className = "window_cells";
cell3.innerHTML = "<textarea rows=\"4\" cols=\"30\"> </textarea>";
cell3.className = "window_cells";
}
window.onload = function() {
genTab();
}
<div id="content"></div>
Basically I am making a table which insert rows with click function.
When row is inserted user will select a value form dropdown menu. And according to that value new cells will be inserted in that perticular row.
I have added the whole functionality. But Problem I am getting here Every Time I select From Drop Down Menu It always alert 0. But not actual value.
Can any one tell what I am doing wrong here.
Another Error is. on first attempt of row selection rownum holds undefined value.
This is the whole code of document.
var counter = 2;
var rownum;
var selectedvalue;
function myFunction() {
if (counter > 5) {
alert("Only 5 Rooms selection is allow ! ");
return false;
} else {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell3 = row.insertCell(0);
var cell4 = row.insertCell(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "<tr><td><label>Room # " + counter + ": </label></td>";
cell2.innerHTML = "<td><select ><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option></select></td> ";
cell3.innerHTML = "<td><select id='child1' onchange='ofChild()' ><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option></select></td>";
counter++;
}
}
function ofChild() {
var e = document.getElementById("child1");
selectedvalue = e.options[e.selectedIndex].value;
alert(selectedvalue);
$('#myTable').find('tr').click(function() {
rownum = $(this).index()
});
var firstRow = document.getElementById("myTable").rows[rownum];
alert('You clicked row ' + (rownum));
// in forloop selectedvalue will be in condition, 3 is just to check
for (i = 0; i < 3; i++) {
var x = firstRow.insertCell(-1);
x.innerHTML = "<td><select><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option></select></td> </tr>";
}
}
function myDeleteFunction() {
if (counter < 2) {
return false;
} else {
document.getElementById("myTable").deleteRow(-1);
counter--;
}
}
div {
padding: 8px;
}
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
</head>
<body>
<div id='TextBoxesGroup'>
<div align="center">
<table id="myTable" style="width:50%" class="table">
<tr class="success">
<td>
<label>Room</label>
</td>
<td>Adults (18+)</td>
<td>Child(0-17)</td>
<td>Child Age</td>
</tr>
<!--tr >
<td><label>Room # 1: </label></td>
<td><select ><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option></select></td>
<td><select id="child" onchange="ofChild()"><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option></select></td>
<td><select class="age"><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option></select></td>
</tr-->
</table>
</br>
<input type='button' value='Add Room' onclick="myFunction()" id='addRoom' class="btn btn-success">
<input type='button' value='Remove Room' onclick="myDeleteFunction()" id='removeButton' class="btn btn-danger">
<br>
<br>
<input type='button' value='Search' class="btn btn-primary">
</div>
</body>
</html>
Here is the picture of the output so far
add event listeners in myFunction
function myFunction(elem) {
...
$('#myTable').find('tr').off().on('click', function() {
rownum = $(this).index()
});
...
}
demo http://codepen.io/vorant/pen/wMNyNN?editors=1010