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
Related
Please help me to solve two issues:
1. Make space between each additional textbox that is created from javascript
2. Align (from left at some position)the textboxes that are created from javascript with another textbox created from jsp
so basically, there is a textbox from JSP on the JSP page, when user clicks on Add button, the Javascript code adds additional textbox each time. I want the existing box from jsp and the addtional textboxes from javascript align at certain position from left and space between each textbox from javascript.
Thanks in advance
The Javascript and jsp code are below:
<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";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.name = "choiceEntry";
element2.type = "text";
element2.size = "100";
cell3.appendChild(element2);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; 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>
<html>
<form method="post" action="poll_save.jsp">
<TABLE id="dataTable" width="350px" border="0">
<TR>
<!-- <TD> 1 </TD>-->
<TD><INPUT type="text" class="bigText" value="
<%=choice.getChoiceEntry()%>" size = "100" name="choiceEntry"/> </TD>
<TD> <INPUT type="checkbox" name="chk"/></TD>
</TR>
</TABLE>
I'm not sure of what you want, but if you only want a vertical spacing and a left margin between inputs you'll be fine with this:
form[action="poll_save.jsp"] table input {
/* Your left offset here */
margin-left: 125px;
margin-top: 32px;
}
And for the code, add new inputs can be done in many ways, one might be:
const addOne = document.querySelector('#add-one');
const table = document.querySelector('#dataTable tbody');
let i = 0;
addOne.addEventListener('click', () => {
table.innerHTML += `
<tr>
<td>
<input name="input-${i++}" type="text" />
</td>
</tr>
`;
});
Perhaps you might want something more flexible? I mean like making them align to the center of their container? If that's the case, please provide a sketch of what you want to make it clearer.
Also my personal recommendation is that you move your style needs to css, do not leave them in the tags (Things such as <table width="..." ...>) and to not use IDs, or only IDs, I recommend you to add classes, specially for styling.
Here you have a working example: https://jsfiddle.net/sigmasoldier/kw8x3b42/2/
Note that there the JSP input is not written in JSP, but you can image that it has the JSP syntax.
I've run with a problem with my web app.
Here's my code:
#app.route('/addrec',methods = ['POST', 'GET'])
def addrec():
if g.user:
if request.method == 'POST':
#UPPER PANE
payor = request.form['payor']
receiptno = request.form['OR']
paymentmethod = request.form['paymentmethod']
naive_dt = time.strftime("%m/%d/%Y")
collectiondate = naive_dt = datetime.now()
message = request.form['message']
#LOWER PANE
url_to_scrape = 'http://localhost:5000/form'
r = requests.get(url_to_scrape)
soup = BeautifulSoup(r.text)
nature = []
for table_row in soup.select("table.inmatesList tr"):
cells = table_row.findAll('td')
if len(cells) > 0:
nature = cells[0].text.strip()
natureamt = cells[1].text.strip()
nature = {'nature': nature, 'nature': natureamt}
nature_list.append(nature)
ent = Entry(receiptno, payor,officer, paymentmethod, collectiondate,message, nature_list)
add_entry(ent)
actions="Applied"
return redirect(url_for('form'))
return redirect(url_for('home'))
As you can see I am getting each of the values from my forms and is scraping the values in my table using beautifulsoup. However after I click the submit button, it loads forever. I am getting the valeus from the upper pane but not in the table.
By the way I am generating my cells from a javascript function onClick. Just in case my javascript might be the problem. or maybe there's an easy way to extract these values from the javascrip functions -> python. Here's my javascript code and HTML
<script type="text/javascript">
function deleteRow(o){
var p=o.parentNode.parentNode;
p.parentNode.removeChild(p);
}
function addRow()
{
var table = document.getElementById("datatable"),
newRow = table.insertRow(table.length),
cell1 = newRow.insertCell(0),
cell2 = newRow.insertCell(1),
cell3 = newRow.insertCell(2),
name = document.getElementById("form").value,
amount = document.getElementById("amount").value;
delete1 = delete1 = '<input type="button" class="btn btn-danger" class="glyphicon glyphicon-trash"id="delete" value="Delete" onclick="deleteRow(this)">';
cell1.innerHTML = name;
cell2.innerHTML = amount;
cell3.innerHTML = delete1;
findTotal();
}
function findTotal(){
var arr = document.querySelectorAll("#datatable td:nth-child(2)");
var tot=0;
for(var i=0;i<arr.length;i++){
var enter_value = Number(arr[i].textContent)
if(enter_value)
tot += Number(arr[i].textContent);
}
document.getElementById('total').value = tot;
}
</script>
HTML:
<form name="noc">
<input class="form-control input-lg" id="form" list="languages" placeholder="Search" type="text" required>
<br>
<input class="form-control input-lg" id="amount" list="languages" placeholder="Amount" type="number" required>
<br>
<button onclick="addRow(); return false;">Add Item</button>
</form>
<table id="datatable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Nature of Collection</th>
<th>Amount</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
The data of these scraped values, I expect them to be saved to my database. On a cell. If possible I would like the list to be inserted in a column so I can get them later.
Or is there a way I can get the lists on a cleaner and better way to my database? Any help is appreciated. Thank you!
So it looks like you're using requests to try and get data generated by JS. Well this isn't going to work, unless you know some magic a lot of people don't. Requests can't deal with the JS, so it never runs. You should be able to get the data using selenium or something to automate a browser. Otherwise, I don't think you're going to be able to scrape it like this. But if someone knows a way to get JS generated data with requests, please post it.
I have a form like that:
<form>
<table id="table">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>SVNr</th>
</tr>
<tr>
<td contenteditable="true">Jill</td>
<td contenteditable="true">Smith</td>
<td class="svnr" contenteditable="true">50</td>
<td><input type="submit" value="Remove" onclick="DeleteRow(this)"></td>
</tr>
<tr>
<td contenteditable="true">Eve</td>
<td contenteditable="true">Jackson</td>
<td class="svnr" contenteditable="true">94</td>
<td><input type="submit" value="Remove" onclick="DeleteRow(this)"></td>
</tr>
</table>
<input type="button" value="Save Changes">
</form>
This one works perfectly. Futhermore, I want to add table rows to my table programmatically.
I do it this way:
count = numberOfRows;
formular[count] = new Object();
formular[count]["Firstname"] = document.getElementById("Firstname").value;
formular[count]["Lastname"] = document.getElementById("Lastname").value;
formular[count]["SVNr"] = document.getElementById("SVNr").value;
var table = document.getElementById("table");
var TR = table.insertRow(count);
var TD = document.createElement("td");
TD.setAttribute("contenteditable", "true");
var TD2 = document.createElement("td");
TD2.setAttribute("contenteditable", "true");
var TD3 = document.createElement("td");
TD3.setAttribute("contenteditable", "true");
TD3.className = "svnr";
var TD4 = document.createElement("td");
var TXT = document.createTextNode(formular[count]["Firstname"]);
var TXT2 = document.createTextNode(formular[count]["Lastname"]);
var TXT3 = document.createTextNode(formular[count]["SVNr"]);
var Input = document.createElement("input");
Input.type = "submit";
Input.value = "Remove";
Input.onclick = "DeleteRow(this);";
TD.appendChild(TXT);
TR.appendChild(TD);
TD2.appendChild(TXT2);
TR.appendChild(TD2);
TD3.appendChild(TXT3);
TR.appendChild(TD3);
TD4.appendChild(Input);
TR.appendChild(TD4);
document.getElementById("Firstname").value = "";
document.getElementById("Lastname").value = "";
document.getElementById("SVNr").value = "";
Also this code is working well. The only problem is that the Remove function doesn't work correctly for the table rows I added programmatically.
My Removing function looks like that:
function DeleteRow(o) {
var p = o.parentNode.parentNode;
p.parentNode.removeChild(p);
}
This function removes ALL programmatically added values if I press the button for one of them. This function works for the 2 entries in the form I didn't add programmatically but as I said, if I press the Remove button for one of added entries, it removes all programmatically added rows and not just the chosen one.
You need to add in something to uniquely identify each tr. You could set a custom attribute on each tr, set a unique id, etc. and pass the unique value to the delete function.
In addition you may find it easier to work with tables by using the DOMTable properties & methods:
http://www.javascriptkit.com/domref/tableproperties.shtml
http://www.javascriptkit.com/domref/tablemethods.shtml
I am creating a program that connects to Firebase Realtime Database and displays the value in a table.
Her is my code:
var leadsRef = database.ref('leads/'+leadID);
var table = document.getElementById('remarksTable');
leadsRef.on('child_added', function(snapshot) {
var remark = snapshot.val().remark;
var timestamp = snapshot.val().timestamp;
var row = document.createElement('tr');
var rowData1 = document.createElement('td');
var rowData2 = document.createElement('td');
var rowData3 = document.createElement('td');
var rowDataText1 = document.createTextNode(remark);
var rowDataText2 = document.createTextNode(timestamp);
var rowDataText3 = document.createTextNode("Some text");
rowData1.appendChild(rowDataText1);
rowData2.appendChild(rowDataText2);
rowData3.appendChild(rowDataText3);
row.appendChild(rowData1);
row.appendChild(rowData2);
row.appendChild(rowData3);
table.appendChild(row);
});
leadID is an ID which I get from the current url, it contains the correct value so no issues there, path is also absolutely right.
Here is the table code:
<table class="table table-bordered" id="remarksTable">
<tr>
<th><strong>Created On</strong></th>
<th><strong>Timestamp 2</strong></th>
<th><strong>Remarks</strong></th>
</tr>
<tr>
<td>12312313231</td>
<td>12312312312</td>
<td>just a remark.</td>
</tr>
</table>
Now, when I run the page, it connects to the Firebase database and loads the required values, creates table row and table data, attaches text to it and then finally attaches the row to table with the id of remarksTable but it is not creating rows properly. Please note the table is creating using Bootstrap.
This is how it looks:
As you can see, the first row displays fine but the next 2 rows which were created by javascript looks a bit different.
The most likely reason is that you are appending the new row to the table element and not the tbody element inside it, which is interacting poorly with the stylesheet that you didn't include in the question.
Note that all tables have a tbody element. The start and end tags for it are optional so it will be inserted by HTML parsing rules if you don't provide one (or more) explicitly).
#Quentin is right, or you can simply add new rows this way:
var table = document.getElementById("remarksTable");
var row = table.insertRow();
var rowData1 = row.insertCell(0);
var rowData2 = row.insertCell(1);
var rowData2 = row.insertCell(2);
rowData1.innerHTML = remark;
rowData2.innerHTML = timestamp;
rowData3.innerHTML = "some text";
Here is a working demo
function addCells() {
var table = document.getElementById("remarksTable");
var row = table.insertRow();
var rowData1 = row.insertCell(0);
var rowData2 = row.insertCell(1);
var rowData3 = row.insertCell(2);
rowData1.innerHTML = "your remark";
rowData2.innerHTML = "your timestamp timestamp";
rowData3.innerHTML = "some text";
}
<table id="remarksTable" border=1>
<tr>
<td>first cell</td>
<td>2nd cell</td>
<td>3rd cell</td>
</tr>
</table>
<button onclick="addCells()">Add New</button>
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);
});
});