I want the table to be visible only after the submit button clicks. But it's not staying on the screen as it is supposed to be. Once I click the submit button, the table comes up for a second and then again becomes invisible. Please let me know what I am doing wrong in my code. Also please let me know if there is any other way to do it.
index.html
<form action="#" id="form" method="post">
<div style="margin-left: 2rem;">
<!-- <input type="submit" value="Submit" id="btn" onclick="hide()"> -->
<input type="button" value="Submit" id="btn" onclick="hide()">
</div>
</form>
<div style="margin-top: 4rem; display: flex; justify-content: center; align-content: center;">
<table style="display: none;" id="table">
<tbody>
<tr>
<th scope="row">Profile No. : </th>
<td>{{ProfileNo}}</td>
</tr>
<tr>
<th scope="row">Name : </th>
<td>{{Name}}</td>
</tr>
</tbody>
</table>
</div>
<script>
function hide() {
document.getElementById("form").submit();
let table = document.getElementById("table");
if (table.style.display === 'none') {
table.style.display = 'table';
}
}
</script>
CodePudding user response:
You need to use AJAX for this to work. If you do it like this, the submit button performs a POST request to the server, and therefore you refresh the page again.
Here's a good solution for you to work with: https://www.pluralsight.com/guides/work-with-ajax-django
CodePudding user response:
You can do this in Django in a following way:
views.py: `
def contact(request):
if request.method == "POST":
message_name = request.POST['message-name']
# message-name has to be in your form
# do something with the data in your view
return render(request, 'template.html', {'message_name': message_name})
#return a variable message_name to the context
template.html:
{% if message_name %}
<center><h2><table id="your table"><tr><td></td></tr></h2></center>
{% else %}
<form action="#" method="post">{% csrf_token %}
<div >
<div>
<input type="text" name="message-name">
</div>
<button type="submit">Display table</button>
</form>
{% endif %}
` You can use input type hidden if you do not want to display any field in the form. The idea is capture the variable from the POST (message-name) and rely on it in the view (message_name)