get All the text fields data from the html table - javascript

Get All the data values from the auto generated table and show these values through loop to user by JavaScript alert.I have implemented but it is not showing anything in alert.how i can take the values from these autogenrated text fields.
function myFunction() {
var table = document.getElementById("myTable");
var table1 = document.getElementById("myTable").length;
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var textf1 = '<div>FirstName:<input type="text" value="Enter Your Name" id="text1" /></div>';
var textf2 = '<div>LastName:<input type="text" value="Enter Your Surname" id="text2" /></div>';
cell1.innerHTML = textf1;
cell2.innerHTML = textf2;
}
function first(){
var x = document.getElementById("myTable");
var textn = "";
var texts= "";
var i;
var a;
for (i = 0; i < x.length ;i++) {
textn += text1[i].value + "<br>";
}
for (a = 0; i < x.length ;i++) {
texts += text2[i].value + "<br>";
}
alert("First Name:"+textn"Second Name:"+texts);
/*var table1 = document.getElementById("myTable").length;
for(var row = 0; row <= table1;row++ ) {
alert("Hello" + text1.value(i) + "Your Surname Is " + text2.value(i) + " You Have Chosen");
}
/*return myFunction()*/
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/myweb.js">
</script>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<table id="myTable"></table>
<table id="myTable1"></table>
<br>
<div id="first"></div>
<button onclick="myFunction()">Add Your First row</button>
<button onclick="first()">Submit</button>
</body>
</html>

function first(){
var x = document.getElementById("myTable");
var inputElements = x.querySelectorAll('input, select, textarea');
for(var i = 0; i < inputElements.length; i++){
alert(inputElements[i].value);
}
}

alert("First Name:"+textn"Second Name:"+texts);
Missing +
alert("First Name:"+textn+"Second Name:"+texts);

Related

Unable to generate table after clearing table

I'm working on a project but am stuck on the fact that I'm unable to generate a new table after resetting the previous table.
What I would like to do is to let a user reset the table using the button and then generate another one if needed, and not needing him to reload the page. However, I am unsure why my codes only allow me to reset the table but am unable to generate another table.
Any help on this would be greatly appreciated.
function generate() {
var myTable = document.getElementById("generatedTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var rows = document.getElementById("rows").value;
var cols = document.getElementById("cols").value;
for (var y = 0; y < rows; y++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var x = 0; x < cols; x++) {
var td = document.createElement('TD');
td.width = 10;
td.height = 10;
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id", cellID.toString());
td.addEventListener("click", function() {
cellClicked(this);
});
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
myTable.appendChild(table);
}
//document.getElementById("button").disabled = true;
}
function cellClicked(cell) {
//var cell = document.getElementById("this");
cell.style.backgroundColor = "yellow";
}
function mouseOver(cell) {
var cell = document.getElementById("td");
cell.style.backgroundColor = "red";
}
function mouseOut(cell) {
var cell = document.getElementById("generatedTable");
cell.style.backgroundColor = "";
}
function removeTable() {
var removeTab = document.getElementById('generatedTable');
var parentElement = removeTab.parentElement;
parentElement.removeChild(removeTab);
}
No. of Rows <input type="text" name="rows" id="rows">
<br>
<br> No. of Cols <input type="text" name="cols" id="cols">
<br>
<button onclick="generate()" type="button" id="button">Generate</button>
<button onclick="removeTable()" type="reset" value="reset">RESET TABLE</button>
<table id="generatedTable" onmouseover="mouseOver()" onmouseout="mouseOut()"></table>
You were using the id "generatedTable" in a confusing way, at the same time for the newly generated table and for the table you already had in your html file. And at the end you were removing the wrapper table instead of the newly generated one.
It is maybe easier to understand if you use a target element and add the table in it:
const wrapper = document.getElementById('table-wrapper');
function generate() {
var table = document.createElement('TABLE');
table.id = 'generatedTable';
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var rows = document.getElementById("rows").value;
var cols = document.getElementById("cols").value;
for (var y = 0; y < rows; y++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var x = 0; x < cols; x++) {
var td = document.createElement('TD');
td.width = 10;
td.height = 10;
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id", cellID.toString());
td.addEventListener("click", function() {
cellClicked(this);
});
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
wrapper.appendChild(table);
}
//document.getElementById("button").disabled = true;
}
function cellClicked(cell) {
//var cell = document.getElementById("this");
cell.style.backgroundColor = "yellow";
}
function mouseOver(cell) {
var cell = document.getElementById("td");
cell.style.backgroundColor = "red";
}
function mouseOut(cell) {
var cell = document.getElementById("generatedTable");
cell.style.backgroundColor = "";
}
function removeTable() {
var removeTab = document.getElementById('generatedTable');
wrapper.removeChild(removeTab);
}
No. of Rows <input type="text" name="rows" id="rows">
<br>
<br> No. of Cols <input type="text" name="cols" id="cols">
<br>
<button onclick="generate()" type="button" id="button">Generate</button>
<button onclick="removeTable()" type="reset" value="reset">RESET TABLE</button>
<div id="table-wrapper"></div>

Creating a JS function that colors a specific cell

I am trying to create a separate function that once a table has been generated, a value x and y can be placed within the input and it will highlight the desired cell a certain colour.
My issue arises when I try to select the cell specifically, my code breaks down at
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
// functions to create values of r and c
function GenerateTable() {
var tblBody = document.createElement("tbody");
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
//selector function
function SelectCell() {
//grab value from the input x and y
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td");
//insert the value of x and y into an array retriever
var rowIndex = document.getElementById("valy").value;
var cellIndex = document.getElementById("valx").value;
//*********BREAKS DOWN HERE*******
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
change.style.backgroundColor = "red";
//change color of specific coord
}
<label>Rows</label>
<input type="number" id="irow">
<label>Cols</label>
<input type="number" id="icol">
<input type="submit" id="smit1">
<input type="number" id="valx" placeholder="x">
<input type="number" id="valy" placeholder="y">
<input type="submit" id="smit2">
<table id="table">
</table>
I'm not sure you can chain it like this:
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
I think what you want is:
//grab value from the input x and y
var rowIndex = +document.getElementById('valy').value;
var cellIndex = +document.getElementById('valx').value;
// Get reference to the table
var table = document.getElementById('table');
// Get the tr of the table with the index rowIndex
var tr = table.querySelectorAll('tr')[rowIndex];
// Query the selected row for all column elements and select the one at the needed index
var change = tr.querySelectorAll('td')[cellIndex];
NOTE: It's probably best to validate the values in the input before trying to retrieve the DOM element to ensure the code does not break if the user enters a non integer value or a value which is out of bounds
Since I finished it anyway:
Here is a working example
var irow = document.querySelector('#irow');
var icol = document.querySelector('#icol');
var smit1 = document.querySelector('#smit1');
var valx = document.querySelector('#valx');
var valy = document.querySelector('#valy');
var smit2 = document.querySelector('#smit2');
function GenerateTable() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
tbl.setAttribute('class', 'generated');
tbl.appendChild(tblBody);
body.appendChild(tbl);
smit1.disabled = true;
irow.disabled = true;
icol.disabled = true;
smit2.disabled = false;
valx.disabled = false;
valy.disabled = false;
}
function SelectCell() {
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td");
var rowIndex = valy.value;
var cellIndex = valx.value;
var change = document.querySelector('table.generated tbody').children[rowIndex].children[cellIndex];
change.style.backgroundColor = "red";
}
smit1.addEventListener('click', GenerateTable);
smit2.addEventListener('click', SelectCell);
table.generated td {
width: 10px;
height: 10px;
border: 1px solid #000000;
}
.width100 {
width: 100%;
}
<body>
<div class="width100">
<input type="number" id="irow" placeholder="rows">
<input type="number" id="icol" placeholder="cols">
<input type="submit" id="smit1">
</div>
<div class="width100">
<input type="number" id="valx" disabled="true" placeholder="x">
<input type="number" id="valy" disabled="true" placeholder="y">
<input type="submit" id="smit2" disabled="true">
</div>
</body>

Recalculate total when table row is deleted

Here is the fiddle. What I want is recalculate the total when I delete a row. I tried this, but it doesn't work:
tot -= parseInt(table.rows[i].cells[1].innerHTML)
table.deleteRow(i);
rowCount--;
i--;
Here is my code:
<div class="lorr">
<table id="myTable" border="1">
</table>
<br />
</div>
<button id="deletes">Remove Checked</button>
<button type="button" onclick="displayResult()">Insert new row</button>
<div id="total">
</div>
<script type="text/javascript">
function displayResult()
{
var swap = '<input type="checkbox" class="escondeyou">';
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = swap+"NEW CELL1ffffffffffffffffff ui7iytuiui riuiui ri";
cell2.innerHTML = "600";
cell2.style.fontWeight="bold";
cell2.style.wordBreak="keep-all";
var tot = "RD$"+document.getElementById("total").innerHTML;
// ******************** Important part ******************************
var tot=0;
for(var i=0;i<=rowCount;i++){
tot += parseInt(table.rows[i].cells[1].innerHTML);
}
document.getElementById("total").innerHTML=tot;
};
</script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here is working: http://jsfiddle.net/joansuriel/QmHdL/50/
Here is what your click handler should do without changing too much your code. Note that you can reuse the calcTotal but be carefoul, I loop until i < table.rows.length
$('#deletes').click(function(){
$("table input[type='checkbox']:checked").parent().parent().remove();
calcTotal(document.getElementById("myTable"), document.getElementById("total"));
});
function calcTotal(table, total){
var tot = 0;
for(var i=0;i<table.rows.length;i++){
tot += parseInt(table.rows[i].cells[1].innerHTML);
}
total.innerHTML=tot;
}
So you have a delete method, just do something with it.
Your code:
$('#deletes').click(function(){
$("table input[type='checkbox']:checked").parent().parent().remove();
});
Change to:
$('#deletes').click(function(){
$("table input[type='checkbox']:checked").parent().parent().remove();
var $table = document.getElementById("myTable");
var total = 0;
for (var i=0; i < $table.rows.length; i++) {
var currentRow = $table.rows[i];
total = total + parseInt(currentRow.cells[currentRow.cells.length - 1].innerHTML);
}
document.getElementById("total").innerHTML = total.toString();
});
Comment me if you have any question.

Simple JavaScript HTML table generator

This is JavaScript HTML table generator.
Input (from textarea)
<label> <content> //each line
Order by <label>
I need to input the values like that:
Input Values
or
A 1
A 2
A 3
B 1
B 2
C 1
C 2
C 3
C 4
And the output should be :
Example
Here is the problem. I don't have ideas to finish my work, but i try my best to code.Can anyone help me?Please!!
function progress(){
var txt = document.form.txt.value;
var line = txt.split("\n"); // every line of context
var line_num = line.length; // total line
for (var i = 0; i<line_num; i++)
{
var seq = line[i].split(" "); //seq[0]: name of label, seq[1] : context
// CODE START
// CODE END
}
var out="<table>"; // if the value exist, using table to display
// CODE START
// CODE END
out=out+"</table>"
document.getElementById('out').innerHTML=out; // display the result
}
And the html code:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title> HW3 </title>
<script type="text/javascript" src="abc.js"></script>
<style type = "text/css">
table
{
width: 300px;
border:1px solid black;
border-collapse : collapse;
}
tr td
{
border:1px solid black;
}
</style>
</head>
<body>
<form name = "form" enctype="multipart/form-data" id="form" method="post" onsubmit="return false;">
<label><textarea name="txt" rows="20" cols = "40"></textarea></label>
<br>
<button type="submit" onclick = "javascript:progress()">Submit</button>
</form>
<p id= "out"></p>
</body>
</html>
I have create sample based on your requirement.
Please check this code.
function progress(){
var txt = document.form.txt.value;
var line = txt.split("\n"); // every line of context
var line_num = line.length; // total line
var uniqueValue = [];
var values = [];
for (var i = 0; i<line_num; i++)
{
var seq = line[i].split(" "); //seq[0]: name of label, seq[1] : context
if (uniqueValue.indexOf(seq[0]) == -1)
{
uniqueValue.push(seq[0]);
values[uniqueValue.indexOf(seq[0])] = new Array();
}
values[uniqueValue.indexOf(seq[0])].push(seq[1]);
}
var maxLength = 0;
var length = values.length;
for (i = 0; i < length; i++)
{
if(values[i].length > maxLength)
maxLength = values[i].length
}
if (length > 0)
{
var out = "<table>"; // if the value exist, using table to display
for (var i = 0; i <= maxLength; i++)
{
out = out + "<tr>"
for (var j = 0; j < length; j++)
{
if(i==0)
{
out = out+ "<th>"+ uniqueValue[j] +"</th>";
}
else
{
if (values[j][i - 1])
out = out + "<td>" + values[j][i - 1] + "</td>";
else
out = out + "<td></td>";
}
}
out = out + "</tr>"
}
out = out + "</table>"
}
document.getElementById('out').innerHTML=out; // display the result
}
table
{
width: 300px;
border:1px solid black;
border-collapse : collapse;
}
tr td, tr th
{
border:1px solid black;
}
<form name = "form" enctype="multipart/form-data" id="form" method="post" onsubmit="return false;">
<label><textarea name="txt" rows="20" cols = "40"></textarea></label>
<br>
<button type="submit" onclick = "javascript:progress()">Submit</button>
</form>
<p id= "out"></p>
Hope this will help you.
I gave it a try too. This approach should give you the big idea behind the dynamically created DOM elements. I think this is a more production-friendly version of the algorithm, given that only native JS is being used.
The main difference with my approach is that it works entirely with dynamic DOM Elements to build the table instead of static html markup. In some cases it can be easier to read and more flexible, especially if you want to work with tag attributes dynamically. I also managed to reduce the complexity by 1 level. Here's my try at it to make it simple and readable:
document.getElementById("btn").addEventListener("click", function(event) {
progress();
}, false);
function progress(){
var txt = document.form.txt.value;
var line = txt.split("\n"); // every line of context
var line_num = line.length; // total line
// Build label->content association
var inputs = {};
for (var i = 0; i<line_num; i++)
{
if (line[i] != "") {
var seq = line[i].split(" "); //seq[0]: name of label, seq[1] : context
var label = seq[0];
var content = seq[1];
if (inputs[label] === undefined) {
inputs[label] = [content];
} else {
inputs[label].push(content);
}
}
}
// For a given MxN table output
var M = Object.keys(inputs).length;
var N = 0; // Unknown for now
var tableElement = document.createElement("table");
tableElement.id = "out";
// Generate header
var headerElement = document.createElement("tr");
for (var label in inputs) {
var tdElement = document.createElement("td");
tdElement.appendChild(document.createTextNode(label));
headerElement.appendChild(tdElement);
// calculate N dimension
var contents = inputs[label].length;
if (N < contents) {
N = contents;
}
}
tableElement.appendChild(headerElement);
// Generate rows
for (var i=0; i<N; i++) {
var trElement = document.createElement("tr");
for (var j=0; j<M; j++) {
var tdElement = document.createElement("td");
var label = Object.keys(inputs)[j];
if (inputs[label].length > i) {
var content = inputs[label][i];
tdElement.appendChild(document.createTextNode(content));
}
trElement.appendChild(tdElement);
}
tableElement.appendChild(trElement);
}
var out = document.getElementById('out');
out.parentNode.removeChild(out);
document.body.appendChild(tableElement); // display the result
}
table {border-collapse:collapse;}
tr,td {border:solid 1px #000;}
td {width:100px;}
<form name = "form" enctype="multipart/form-data" id="form" method="post" onsubmit="return false;">
<label>
<textarea name="txt" rows="20" cols = "40">
A 1
A 2
A 3
B 1
B 2
C 1
C 2
C 3
C 4
</textarea>
</label>
<br>
<button id="btn" type="submit">Submit</button>
</form>
<p id= "out"></p>
Hope this helps.
Have a nice one!

How can I use for loop to newline the table and clear the data?

I want to use forloop to new line the data (not in a row) and when I click the button, clear the last data (but remain the original title--id.lat.lng.speed.rpm.angle.state.time).
Extra, I found at the row back 2 fields aren't have any data. (WHY? Can I remove it?)
<!DOCTYPE html>
<%# page language="java" contentType="text/html;charset=utf-8" import="java.io.*" import="java.util.*" import="java.sql.*"%>
<html>
<head>
<script>
function click_x(clicked_id){
var xxx=[];
xxx[0] = [0,1,2,3,4,5,6,7];
xxx[1] = [8,9,10,11,12,13,14,15];
xxx[2] = [16,17,18,19,20,21,22,23];
xxx[3] = [24,25,26,27,28,29,30,31];
xxx[4] = [32,33,34,35,36,37,38,39];
xxx[5] = [40,41,42,43,44,45,46,47];
var table = document.getElementById("myTable");
var row1 = table.insertRow(1);
var cell1 = row1.insertCell(0);
var markersControlArray = [true,true,true,false,false];
for(var k = 0 ; k < markersControlArray.length ; k++){
if(markersControlArray[k] == true){
for(var i = 0; i < 8 ; i++){
cell1 = row1.insertCell(i);
cell1.innerHTML = xxx[k][i];
}
}
}
}
</script>
</head>
<body>
<table id="myTable" border="3">
<tr>
<th>Id</th>
<th>Lat</th>
<th>Lng</th>
<th>Speed</th>
<th>Rpm</th>
<th>Angle</th>
<th>State</th>
<th>Time</th>
</tr>
</table><br>
<button id="1" onClick="click_x(this.id)">Submit</button>
</body>
</html>
What you need is to insert new row in a table for each xxx[k] with insertRow method. You should do it at the beginning of the outer for loop. So the loops should look something like that:
for(var k = 0 ; k < markersControlArray.length ; k++){
if(markersControlArray[k] == true){
var row1 = table.insertRow(-1);
for(var i = 0; i < 8 ; i++){
var cell1 = row1.insertCell(i);
cell1.innerHTML = xxx[k][i];
}
}
}
Those empty cells are there because you create them before the loops, with this code:
var cell1 = row1.insertCell(0);
var cell2 = row1.insertCell(1);
Whole JavaScript code:
function click_x(clicked_id){
var xxx=[];
xxx[0] = [0,1,2,3,4,5,6,7];
xxx[1] = [8,9,10,11,12,13,14,15];
xxx[2] = [16,17,18,19,20,21,22,23];
xxx[3] = [24,25,26,27,28,29,30,31];
xxx[4] = [32,33,34,35,36,37,38,39];
xxx[5] = [40,41,42,43,44,45,46,47];
var table = document.getElementById("myTable");
var markersControlArray = [true,true,true,false,false,true]; // you have missed value for xxx[5] - I added it
for(var k = 0 ; k < markersControlArray.length ; k++){
if(markersControlArray[k] == true){
var row1 = table.insertRow(-1);
for(var i = 0; i < 8 ; i++){
var cell1 = row1.insertCell(i);
cell1.innerHTML = xxx[k][i];
}
}
}
}
Check working fiddle.
In general I see that you have used code from some tutorial and didn't analyze it well enough and didn't remove unneeded code.
<!DOCTYPE html>
<html>
<head>
<script>
function arrRow(tableId){
var table = document.getElementById(tableId);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
return row;
}
function click_x(clicked_id){
var xxx=[];
xxx[0] = [0,1,2,3,4,5,6,7];
xxx[1] = [8,9,10,11,12,13,14,15];
xxx[2] = [16,17,18,19,20,21,22,23];
xxx[3] = [24,25,26,27,28,29,30,31];
xxx[4] = [32,33,34,35,36,37,38,39];
xxx[5] = [40,41,42,43,44,45,46,47];
var table = document.getElementById("myTable");
var markersControlArray = [true,true,true,false,false];
for(var k = 0 ; k < markersControlArray.length ; k++){
if(markersControlArray[k] == true){
var RowVar = arrRow("myTable");
for(var i = 0; i < 8 ; i++){
cell1 = RowVar.insertCell(i);
cell1.innerHTML = xxx[k][i];
}
}
}
}
</script>
</head>
<body>
<table id="myTable" border="3">
<tr>
<th>Id</th>
<th>Lat</th>
<th>Lng</th>
<th>Speed</th>
<th>Rpm</th>
<th>Angle</th>
<th>State</th>
<th>Time</th>
</tr>
</table><br>
<button id="1" onClick="click_x(this.id)">Submit</button>
</body>
</html>

Categories

Resources