i Want to add loop to read all html table rows data which are "Input text" and want to show all the "Input text" data according to row as alert by click once on submit this code is only working for one table row data which
is generated
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var textf1 = '<input type="text" value="Fname1" id="text1" />';
var textf2 = '<input type="text" value="Fname2" id="text2" /> ';
cell1.innerHTML = textf1;
cell2.innerHTML = textf2;
cell3.innerHTML = textf4;
}
function first(){
}
alert("Hello"+text1.value+"Your Surname Is "+text2.value+" You Have Chosen");
return myFunction()
}
<
<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="Submit()">Submit</button>
No so much a solution, but this might get you going.
To create a new row...
HTML
<input type="button" id="mybutton">Add Row</button>
jQuery
$('#mybutton').click(function(){
$('#mytable tr:last').after('<tr><td>...</td></tr>');
});
To "loop" through your table...
jQuery
// Each row in your table.
$('#mytable> tbody > tr').each(function (key, row) {
var $row = $(row);
var $input = $row.find(':input');
// Each input for the given row.
$.each($input, function (key, element) {
var $element = $(element);
console.log($element);
});
});
Related
I used code to create a <th>, This below code works fine for the first time but doesn't work when i create them repeatedly,i.e, Again and again.
function createTH(){
var noOfRow = document.getElementById("addItemTable").rows.length;
var temp = document.getElementById("addItemTable");
var table = temp.getElementsByTagName('tbody')[0];
var row = table.insertRow(-1);
var cell2 = row.insertCell(0);
var cell3 = row.insertCell(1);
cell2.innerHTML="this is inside table div";
cell2.style="border: dashed;"
cell3.innerHTML="this is inside another another div";
cell3.style="border: dashed;"
var thContent = '<th class="col2">' + '<br>' + 'test' + '   ' + '*' + '' + '</th>'
var mainTable = document.getElementById("addItemTable");
$('#addItemTable>tbody>tr').prepend(thContent);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody>
</tbody>
</table>
</div>
<input type="button" onclick="createTH()" value="Click to create <th> again and again"/>
My current output is a mess after doing the second click on the button.
My expected output is in following pattern:
<tr>
...
<th><td><td>//I only want to repeat this single line on every click of button.
<th><td><td>
<th><td><td>//I'm looking to create this kind of repetition on click of button.
...
</tr>
For more reference you can visit: Dynamic Creation of th, as this question is continuation of the above mentioned thread. I made a new thread because old thread would become more tedious and the length of question would be increased.
Any help would be greatly appreciated.
The issue is because you're appending thContent to all tr which you select by jQuery, not just the new one. To fix this change the line to only append to the new row instance:
$(row).prepend(thContent);
However it's worth noting that you're using an odd combination of plain JS and jQuery. If you're using jQuery already you can simplify the code drastically:
$('#add').on('click', function() {
var rowHtml = '<tr><th class="col2"><br />test *</th><td>this is inside table div</td><td>this is inside another another div</td></tr>';
$('#addItemTable').append(rowHtml);
});
td { border: dashed; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody></tbody>
</table>
</div>
<button id="add">Click to create <th> again and again</button>
You keep adding to every row.
Use jQuery consistently and it helps. Also DRY: Do not repeat yourself
Like this
const cellStyle = { "style": "border: dashed;" }
$("#addRow").on("click", function() {
const $tb = $("#addItemTable tbody");
let $newRow = $("<tr/>");
$newRow.append('<th class="col2"><br />test *</th>');
$newRow.append($("<td/>", cellStyle).text("this is inside table cell"));
$newRow.append($("<td/>", cellStyle).text("this is inside another table cell"));
$tb.prepend($newRow);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody>
</tbody>
</table>
</div>
<input type="button" id="addRow" value="Click to create <tr> again and again" />
You can use row counter to increase index number of row and append data in it when function calls.
Here is Demo
var rowCounter = 0;
function createTH(){
var noOfRow = document.getElementById("addItemTable").rows.length;
var temp = document.getElementById("addItemTable");
var table = temp.getElementsByTagName('tbody')[0];
var row = table.insertRow(-1);
var cell2 = row.insertCell(0);
var cell3 = row.insertCell(1);
cell2.innerHTML="this is inside table div";
cell2.style="border: dashed;"
cell3.innerHTML="this is inside another another div";
cell3.style="border: dashed;"
var thContent = '<th class="col2">' + '<br>' + 'test' + '   ' + '*' + '' + '</th>'
var mainTable = document.getElementById("addItemTable");
$('#addItemTable>tbody>tr').eq(rowCounter).prepend(thContent);
rowCounter++;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody>
</tbody>
</table>
</div>
<input type="button" onclick="createTH()" value="Click to create <th> again and again"/>
I found one more solution for this question by making use of Outer Html. Just a different approach to this problem.
function createTH() {
var noOfRow = document.getElementById("addItemTable").rows.length;
var temp = document.getElementById("addItemTable");
var table = temp.getElementsByTagName('tbody')[0];
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
elemVal = '<th class="col2">' + "test" + '   ' + '*' + '' + '</th>';
cell1.outerHTML = elemVal;
cell2.innerHTML = "this is inside table div";
cell2.style = "border: dashed;"
cell3.innerHTML = "this is inside another another div";
cell3.style = "border: dashed;"
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-content" id="elementDiv">
<table id="addItemTable">
<tbody>
</tbody>
</table>
</div>
<input type="button" onclick="createTH()" value="Click to create <th> again and again" />
This question already has answers here:
Adding an onclick event to a table row
(12 answers)
Closed 4 years ago.
I am adding rows to an existing table using JavaScript insertRow method
For one cell, I want to add an onclick event.
How can I do that using pure JavaScript?
I am attaching my code.
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell1.onclick()="xfunc()";
}
function xfunc(){
alert("Hi")
}
</script>
</body>
</html>
onclick is a html property, you have assign a function to this property to handler click event.
In you case:
cell1.onclick = xfunc; // instead of cell1.onclick()="xfunc()";
Update your function as below
<script>
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell1.onclick=xfunc;
}
function xfunc(){
alert("Hi")
}
</script>
Use the below one.
cell1.addEventListener('click', xfunc);
First you could try something really simple:
cell1.setAttribute('onclick', 'xfunc()');
Maybe this already Handles your problem.
If not you just could use a DIV inside the cell:
var div = document.createElement('div');
div.setAttribute('onclick', 'xfunc()');
div.setAttribute('style', 'height: 100%; width: 100%');
div.innerHTML = 'NEW CELL1';
cell1.appendChild(div);
This should handle the problem for sure.
The only thing im not really sure about is wether a table-cell is capable of onclick attributes :)
LG
I think the problem is that, How you are attaching the event to cell1? Try the following code:
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell1.onclick = xfunc; //<-- problem was on this line
}
It seems that when I try to retrieve a data for a certain id it populates it's data to all textbox present.
Here is my addrow script that adds a new row of textboxes:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
}
Here is my html file
<td><input type="text" name="personId" class="personId" size="30" onchange="test()"/></td>
<td><input type="text" name="personName" class="personName" size="30" disabled/></td>
Here is the test script which appends that data to the textbox:
function test(){
var $cell = $('.personId');
var cellData = $cell.html();
$cell.data('value', cellData);
//Code here to pass the personId in to an ajax and return it's corresponding personName
success: function(data) {
$('.personName').val(data.person);
}
}
What happens is that when I have 3 rows of personId and personName and I enter one personId all the textboxes in the 3 rows returns the personName. The goal is that when I enter an personId in one row pesonName should only reflect on the textbox i'm currently entering the personId. Please help. Thank you so much.
Follow the comments for understanding code.
var personVal =1; //personVal to create dynamic id
$(document).on('keyup','.personId', function() {
var personId = $(this).val();
//Code here to pass the personId to an ajax and return it's corresponding personName
//ajax success code here
//and success code like
// success: function(data) {
var currentPersonVal=this.id.split('-')[1];
var personName="#personName-"+currentPersonVal;
$(personName).val(currentPersonVal);//name hardcoded for your understanding, you need to add 'data.person'
//}
});
function addRow(tableID) {
var table = document.getElementById(tableID);
personVal =personVal+1 //increase personVal by 1
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
//generate textbox here with dynamic id by adding personVal at the end of id and '-'(dash) is used to split id later
var newcell = row.insertCell(0);
newcell.innerHTML = "<input type='text' id='personId-"+personVal+"' class='personId' size='30' />";
var newcell = row.insertCell(1);
newcell.innerHTML = "<input type='text' id='personName-"+personVal+"' class='personName' size='30' disabled/>";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table align="center" width="100%" id="table1Id" class = "centerAlign">
<td><input type="text" id="personId-1" class="personId" size="30" /></td>
<td><input type="text" id="personName-1" class="personName" size="30" disabled/></td>
</table>
<input type="button" value="Add Row" onclick="addRow('table1Id');"/>
Let me know if you don't understand anything.
You can give personId by data attribute like :
<td><input type="text" name="personId" data-personId = "1" class="personId" size="30" onchange="test()"/></td>
And then after that you can get that personId in like :
$('.personId').attr('data-personId');
In your html file change test() to test(this):
<td><input type="text" name="personId" data-personId = "1" class="personId" size="30" onchange="test()"/></td>
& change your test function to this :
function test(e){
// remove this
// var $cell = $('.personId');
var cellData = $(e).html();
$(e).data('value', cellData);
//Code here to pass the personId in to an ajax and return it's corresponding personName
success: function(data) {
$(e).closest('.personName').val(data.person);
}
}
I am creating a html table using javascript as follows:
var table = document.getElementById("ordertable");
var rowcount = document.getElementById("ordertable").rows.length;
var row = table.insertRow(rowcount);
row.id="row_"+rowcount;
row.className = "rec_unselected";
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4)
I want to add a onmousedown function in in insertion step so I added like follows:
row.innerHTML = "onmousedown='RowClick(this,false);'";
But it is not working!
I am expecting the table like:
`<tr onmousedown="RowClick(this,false);" id="row_1" class="rec_unselected"`>
<td>any value</td>
<td>any value</td>
<td>any value</td>.....................
But I am getting as <tr id="row_1" class="rec_unselected">
Simply add your event listener with JavaScript by doing:
row.onmousedown = function(){ RowClick(this,false); }
What row.innerHTML = "onmousedown='RowClick(this,false);'" does is add that text into the element itself (and not as a onmousedown attribute event).
What you are trying to change is not the innerHTML. But since you are doing this in JS already, you should not move the function call to your HTML, but have it all in your scripts.
You add the click event to your row in JS like this:
row.addEventListener('mousedown', function (event) {
RowClick(event.target, false);
});
I have a HTML table with information. Right now I can add rows and delete the rows with a button using javascript. I can also add the information to the database directly using the Add Rows button, and remove the data from the database with the Delete Rows button. But I don't want to use those buttons because I think it is better to have another button for inserting all the information to the database at once. So I need suggestions on how to read information from a HTML table and inserts its data to a mysql database.
Here is the code:
Right now the code does not insert data to the database.
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
cell3.innerHTML = rowCount;
var cell4 = row.insertCell(3);
cell4.innerHTML = rowCount;
var cell5 = row.insertCell(4);
cell5.innerHTML = rowCount;
var cell6 = row.insertCell(5);
cell6.innerHTML = rowCount;
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=1; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" border="1">
<tr>
<th><INPUT type="checkbox" name="chk[]"/></th>
<th>Make</th>
<th>Model</th>
<th>Description</th>
<th>Start Year</th>
<th>End Year</th>
</tr>
</TABLE>
</BODY>
</HTML>
Yes.. You have good JavaScript code to adding dynamic content..wow..
Now you want to insert that content to MySQL table..yes you can...
Before that small modification to do your code..
First you should understand insert something to database, you have a HTML form element..
and controls..you can add dynamically HTML form element as following
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = "<input type='text' name='item[]'>";
var cell3 = row.insertCell(2);
cell3.innerHTML = "<input type='text' name='price[]' />";
var cell4 = row.insertCell(3);
cell4.innerHTML = "<input type='text' name='qty[]' />";
}
keep your delete method same, but change this line only
var i=1
to
var i=0
Now Change your HTML code as following ,
make sure your table body tag has a id named "dataTable",
and remove you check box ,put form element to cover your table..bang...
<INPUT type="button" value="Add Row" onClick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onClick="deleteRow('dataTable')" />
<form action="" method="post" name="f">
<TABLE width="425" border="1">
<thead>
<tr>
<th width="98"></th>
<th width="94">Item</th>
<th width="121">Price</th>
<th width="84">Qty</th>
</tr>
</thead>
<tbody id="dataTable">
</tbody>
</TABLE>
<INPUT type="submit" value="Insert" name="submit" />
</form>
// create mysql database and then create table
// following is the example
CREATE TABLE `your_table_name` (
`id` int(11) NOT NULL auto_increment,
`item` varchar(200) NOT NULL,
`price` varchar(200) NOT NULL,
`qty` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
greate ... now this is the interesting part..
I use the php language to insert data to database..
make sure you should create database connection..
<?php
if($_POST[submit])
{
foreach ($_POST['item'] as $key => $value)
{
$item = $_POST["item"][$key];
$price = $_POST["price"][$key];
$qty = $_POST["qty"][$key];
$sql = mysql_query("insert into your_table_name values ('','$item', '$price', '$qty')");
}
}
?>
I think this post is important to all ..
First of all you should separate client and server side:
Client is browser, and HTML table is stored in "browser's" memory, all editorial is done on client's computer, you can disconnect from internet and still use this page - and it will work (add/delete rows)
Server's side works on remote server and don't know what rows/columns are inserted into client's HTML table.
So, you need some mechanism to send data from client to server, after you finished.
Second item: HTML table and Relational Database table are different entities, HTML table is only a visual representation of data, relational database table is entity in specific database (you can have several databases, each database can have several tables) stored on disc (on server usually).
HTML table can have dynamic rows/columns, but RD table can have dynamic rows only, NOT columns, (not fairly true, some RDBMS allows removing columns).
Finally - you should solve 2 items:
Sending data from client to server, this can be achieved via placing <form action="phpscript.php">...</form> around <table> and adding "submit" button to it, dont forget to store amount of columns/rows in some "hidden" fields, also - I suppose you need data in this cells, so add <input> in each HTML table cell
Storing data on server - for mysql you really can go with dynamic columns add/remove, but also you can just store ROW and COLUMN index with data, like:
0, 0, dataincell_0_0
1, 0, dataincell_1_0