I have a very simple webpage which is just going to read a text file listing email addresses and write them into a table. Next to each row there is a delete button to delete that specific email from the list. There is also a button to save the data in the table to a file.
I cannot get it to work so I can add rows which are input fields, where users can enter new emails and that will be saved into the file after I press save, and converts the input field to a non-editable text field. Basically I want the user to see the same page without input fields after they click save to file, but the added rows should be included in the table.
This is the code:
from distutils.log import debug
from flask import *
app = Flask(__name__)
data_file = 'emails.txt'
@app.route("/save", methods=["POST"])
def saveEmails():
rows = json.loads(request.form["emails"])
with open(data_file, 'w') as f:
for row in rows:
f.write(row + 'n')
return render_template('index.html', emails=rows)
@app.route("/")
def showData():
data = ["[email protected]", "[email protected]"]
return render_template("index.html", emails = data)
if __name__ == "__main__":
app.run(debug=True)
And this the HTML:
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
Emails
<button onclick="addRow()">Add row</button>
<button onclick="saveEmails()">Save to file</button>
<br>
<table id="data-table">
{% for i in range(emails | length) %}
<tr>
<br><td>{{emails[i]}}</td>
<td><button onclick="deleteRow({{ i }})">Delete</button></td>
</tr>
{% endfor %}
</table>
<script>
function deleteRow(index) {
var table = document.getElementById('data-table');
table.deleteRow(index);
}
function saveEmails() {
var table = document.getElementById('data-table');
var emails = [];
for (var i = 0; rows.length; i++) {
numbers.push(rows[i].cells[0].innerText);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '/save', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('action=save&emails=' + encodeURIComponent(JSON.stringify(emails)));
}
function addRow() {
var table = document.getElementById('data-table');
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var input = document.createElement('input');
input.type = 'text';
cell1.appendChild(input);
var cell2 = row.insertCell(1);
var button = document.createElement('button');
button.textContent = 'Delete';
button.onclick = function() {
var index = table.rows.indexOf(rows);
deleteRow(index);
};
cell2.appendChild(button);
}
</script>
</body>
</html>
1