Getting post data from html table inside a form? Django - javascript

I have a dynamically populated html table that can be edited by an user (they can add rows delete them, etc -this is managed through javascript-).
The problem is, even when the table is inside the form, the server doesn't get any post data from it.
Here is the code for the template:
{% extends 'base.html' %}
{% block content %}
<script>
function add_row(){
var table = document.getElementById("body");
var row = table.insertRow(table.rows + 1);
var cell = row.insertCell(0);
var combo1 = document.createElement("select");
var option;
{% for opt in options_all %}
option = document.createElement("option");
option.setAttribute("value", "{{ opt.id }}");
option.text="{{ opt.description }}";
combo1.add(opcion);
{% endfor %}
cell.appendChild(combo1);
}
</script>
<form action='.' method='post'>
{% csrf_token %}
{{ form.as_p }}
<input type="button" value="New row" onclick="add_row()">
<table id="table_id">
<thead>
<tr>
<th>
Options
</th>
</tr>
</thead>
<tbody id="body">
</tbody>
</table>
<input type='submit' value='Submit'>
</form>
{% endblock %}
How can I get the data from the select elements?? Thanks!!
Edit: I have checked the request element and request.post doesn't have the desired data

SOLVED.
You have to specify a name for each select element inside the table. (Not the option elements)

Related

Javascript does not work in the second page of a data table

Actually I'm working with the following datatable:
Data Table code:
<table aria-describedby="dataTable_info" cellspacing="0" class="table table-hover dataTable" id="dataTable" role="grid" style="width:100%;" width="100%">
<thead>
<tr>
<th>{{'fsaGeneralPlan.table.Auditors'|trans({}, 'FSABundle')}}</th>
<th>{{'fsaGeneralPlan.table.Audits'|trans({}, 'FSABundle')}}</th>
<th>{{'fsaGeneralPlan.table.Areas'|trans({}, 'FSABundle')}}</th>
</tr>
</thead>
<tbody>
{% for audit in auditsByArea %}
{% set myArray = audit.Audits|split(',') %}
{% set AuditsStatus = audit.AuditsStatus|split(',') %}
<tr>
<td>{{ audit.Auditor }}</td>
<td>
{# {% set long = numberOfAudits|length + 2 %} #}
{# <h1>{{ long }}</h1> #}
{% for i in 0..3 %}
{% set e = i + 1 %}
<a title="{{ AuditsStatus[i] }}" class="btn btn-outline-primary btn-sm auditButton {{ AuditsStatus[i] }}" data-id="Audit{{ myArray[i] }}" data-area="{{ audit.area_name }}" data-status="{{ AuditsStatus[i] }}" id="auditButton{{ myArray[i] }}" name="auditButton">{{'w' ~ e }}</a>
{# <input class ="auditButton {{ AuditsStatus[i] }} mx-2" value="{{'W' ~ i }}" href="" data-id="Audit{{ myArray[i] }}" data-area="{{ audit.area_name }}" data-status="{{ AuditsStatus[i] }}" id="auditButton{{ myArray[i] }}" name="auditButton" type='text' readonly ></input> #}
{% endfor %}
</td>
<td>{{ audit.area_name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
And I have this Javascript to change the class of the buttons in the datatable once that the page is loaded:
<script type="text/javascript">
$(document).ready(function(){
$(".auditButton.Submitted").removeClass('btn-outline-primary');
$(".auditButton.Submitted").addClass('btn-outline-success');
$(".auditButton.Expired").addClass('btn-outline-danger');
$(".auditButton.Capturable").addClass('btn-outline-warning');
});
It works correctly but just in the first page of the datatable, it does not work in the other pages.
Any idea or subject of how to fix it or what is wrong?
You need to listen to the draw event for your table.
Why?
Your current setup works fine for the first page, because those elements are all rendered when $(document).ready() fires. However, the other pages are rendered after the document is ready.
Try:
const table = $('#dataTable').DataTable();
// Event listener for DT 1.10+
table.on('draw', function() {
$(".auditButton.Submitted").removeClass('btn-outline-primary');
$(".auditButton.Submitted").addClass('btn-outline-success');
$(".auditButton.Expired").addClass('btn-outline-danger');
$(".auditButton.Capturable").addClass('btn-outline-warning');
});
Doing this, you can also remove the same block of code from `$(document).
You can also place all this inside the draw callback for your datatable if you'd prefer:
const table = $('#dataTable').DataTable({
drawCallback: function(settings) {
// changes in here
}
});

Flask does not return db query when I use the JS hide/unhide. Works if I comment out JS

I am trying to retrieve data from the database based on a users search results. The results, in a table format, should only be shown after the user hits the search button.
Query executes fine when javascript is cancelled out and the table "list" display is changed to block. However, when I enable the javascript I get no results.
<div style="text-align: center;">
{% from "_formhelpers.html" import render_field %}
<form method=post action="/">
<dl style="display: inline-block; text:white;" >{{render_field(form.search)}} </dl>
<button id="searchbutton" type="submit" style="display: inline-block;" class="btn btn-outline-success my-2 my-sm-0" onclick="fetchlist(); return false;">Search</button>
<br>
{% if error %}
<p class = "error"><strong>Error:</strong>{{error}}</p>
{% endif %}
</form>
</div>
<div style="text-align:center;">
<table id="list" style="display:none;" class = "table table-hover" >
<thead>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Rating</th>
<th scope="col">Review</th>
</thead>
<tbody>
{% for row in data %}
<tr>
{% for d in row %}
<td>{{ d }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
<script>
function fetchlist() {
if (document.getElementById('searchbutton').onclick) {
document.getElementById('list').style.display = 'inline';
}
else document.getElementById('list').style.display = 'inline';
}
</script>
{% endblock %}
</html>
#app.route('/', methods=['GET', 'POST'])
def homepage():
try:
form=SearchForm(request.form)
global d1
d1 =""
if request.method == "POST" and form.validate():
search = form.search.data
a = search.split(" ",1)
firstname, lastname = (a[0], a[1])
c,conn = connection()
qry = "SELECT FirstName, LastName FROM posts WHERE FirstName LIKE (%s) AND LastName like (%s)"
c.execute(qry, ((thwart(firstname)), (thwart(lastname))))
d1 = c.fetchall()
c.close()
conn.close()
else: print('error')
return render_template("index.html", data=d1, form = form)
except Exception as e:
return(str(e))
As you already know the problem is caused by your JS. This is because the JS is waiting for the search button to be clicked before it changes the style of the list to inline.
This all seems fine, but the problem comes in the fact that the JS is executed when the button is clicked. But then the request is posted to the server and a new page is sent to the browser with the search results. However, this new page the search button has never been clicked.
You can fix writing the method to display the results into your template. For instance you could wrap the table in an if statement like this...
{% if data|length %}
<div style="text-align:center;">
<table id="list" style="display:none;" class = "table table-hover" >
<thead>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Rating</th>
<th scope="col">Review</th>
</thead>
<tbody>
{% for row in data %}
<tr>
{% for d in row %}
<td>{{ d }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table
</div>
{% endif %}
The |length filter makes sure data is not an empty string. Otherwise I believe it may always be true. You could try {% if data %} to double check. It may work.
There are a lot more options....
You could wrap you <script> in the if statement. You should modify it a little. So it does not wait of the search button to be clicked.
You could wrap the inline style in the if statement. Of course you could use CSS classes instead of inline styling. This would be cleaner.

Dynamic querySelector with Dynamic Jinja HTML

I have forms that are rendered dynamically based on values in a dictionary. They are given an ID based on the key value. They are all initially hidden.
<div id="subforms" style="display: none" >
{%for k, v in options.items() %}
<h3>{{k}}:</h3>
<form id= "{{k}}">
{% for option in v %}
<label>{{option}}</label>
<input type="checkbox" name="{{option}}_enabled">
{% endfor %}
</form>
{% endfor %}
</div>
I now create an input list with those same keys:
<form action="/action_page.php">
<input list="tables" id="tablelist" >
<datalist id="tables">
{% for key in options.keys() %}
<option value={{key}}>
{% endfor %}
</datalist>
</form>
Last I have Javascript used to listen to the tablelist element and select a form based on the inputlist's value.
const tables = document.getElementById("tablelist")
const subform_block = document.getElementById("subform_display")
const forms = document.getElementById("subforms")
tables.oninput = () => {
let form =
forms.querySelector('form[id="${tables.value}"]');
if(form){
subform_block.innerHTML = form.outerHTML;
}
else {
subform_block.innerHTML = "not found";
}
}
The querySelector is not working. I confirmed that the HTML is rendered correctly and the IDs are consistent, but my querySelector is unable to find any of the forms. What is wrong?
Changed:
let form = forms.querySelector('form[id="${tables.value}"]');
to:
document.querySelector('form[id=' + tables.value + ']');
And it works. Not sure why ${tables.value} wasn't recognized properly

How to add n forms using jquery

Here I found the following helpful javascript to dynamically add a form to my python/django template. Here is the code:
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+)');
var replacement = prefix + '-' + ndx;
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function addForm(btn, prefix) {
// Make a variable and assign to it a string convertd to an integer. The string is the variable
// with the the #id assigned to it. The value of this attribute is saved. The value will equal
// the current number of forms
var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
// Find the element with the given class, and clone it after loading the 0 index get request.
// Var row is now a cloned row.
var row = $('.dynamic-form:first').clone(true).get(0);
$(row).removeAttr('id').insertAfter($('.dynamic-form:last')).children('.hidden').removeClass('hidden');
$(row).children().not(':last').children().each(function() {
updateElementIndex(this, prefix, formCount);
$(this).val('');
});
$(row).find('.delete-row').click(function() {
deleteForm(this, prefix);
});
$('#id_' + prefix + '-TOTAL_FORMS').val(formCount + 1);
return false;
}
function deleteForm(btn, prefix) {
$(btn).parents('.dynamic-form').remove();
var forms = $('.dynamic-form');
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
for (var i=0, formCount=forms.length; i<formCount; i++) {
$(forms.get(i)).children().not(':last').children().each(function() {
updateElementIndex(this, prefix, i);
});
}
return false;
}
Then I have my following template.
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% crispy form form.helper %}
{% load staticfiles %}
{% block extrahead %}
{% endblock %}
{% block blurb %}
<h1>Upload Samples</h1>
<p>Upload A Single Sample, Or A Batch Of Samples</p>
{% endblock %}
{% block form %}
<style>
tr th {text-align:center;}
</style>
<!-- Display formset -->
<form id="myForm" method="post" action="">
{{ formset.management_form }}
<div class='table'>
<table class='no_error' id='id_forms_table' border="2px" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
{% for form in formset %}
<tr id="{{ form.prefix }}-row" class="dynamic-form">
<td></td>
<
<td {% if forloop.first %} class="hidden"{% endif %}>
<a id="remove-{{ form.prefix }}-row" href="javascript:void(0)" class="delete-row"><input type='button' value='Remove Row' class='delete-row'></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</form>
<!-- Dynamic Formset javascript -->
<script type="text/javascript">
$(function () {
$('.add-row').click(function() {
return addForm(this, 'form');
});
$('.delete-row').click(function() {
return deleteForm(this, 'form');
})
$('.add-10-rows').click(function() {
return addForm(this, 'form');
})
})
</script>
<input type='button' value='Add Row' class='add-row'>
<input type='button' value='Add 10 Rows' class='add-10-rows'>
<div style='padding-top:20px'>
<input class='btn btn-primary' type='submit' value='Upload' />
</div>
{% endblock %}
This works great, but now I would like to adjust this to allow for the addition of n rows. I will make a form that takes in an interger, then when a button is pressed, I would like to add that number of forms instead of one at a time. I am quite new to javascript/jquery, but I figured the psudo code would look something like this:
function addNForms(btn, prefix, n){
for(var i = 0; i < n; i++){
// Perform the same logic as addForm.
}
}
Unfortunately I have not been able to figure it out. I have performed the function logic n times in a for loop, but the result was that only one form at a time was being made. Which part of the addForm function can I put in a for loop to achive this goal?

Pass an array of a twig for a jQuery

I have a block on my twig writing a table from a variable received from controller
{% block foot_informations %}
{% if ads is not empty %}
<div class="panel-foot-information row">
<table id="ads">
<thead>
<tr>
<th>Departure</th>
<th>Destination</th>
</tr>
</thead>
<tbody>
{% for ad in ads %}
<tr class="ad-tr">
<td>{{ ad.departure }}</td>
<td>{{ ad.packageType }}</td>
<td>{{ ad.transportation }}</td>
{# <td>{{ ad.date }}</td> #}
<td>select</td>
<td class="hidden"><input type="hidden" id="idLat" value="{{ ad.departureLatitude }}"/></td>
<td class="hidden"><input type="hidden" id="idLong" value="{{ ad.departureLongitude }}"/></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
{% endblock %}
I would like to get this variable month in JQuery to manipulation it and then rewrite my table
to catch it saw something like this: var ads = {{ ads|json_encode() }};
My idea is in a evnto of button to click to change the value of the array and reconstruct the table someone help me?
$('#my_button').click(function () {
alert(ads);
$.each(ads, function(){
alert($(this));
//filter by type package
});
//rewrite table
});
First of all I would suggest that you don't mix two strategies.
is generating views serverside, what you obviously do with the twig templates.
is passing raw data (with AJAX or like your example with the json_encoded array parsed into a JS Object), and then generating the table with JS DOM manipulation.
But that's my opinion about this part.
If you choose for Option 1 you could add/remove classes in your $.each filter-like callback for the table rows you want to hide / show.
And then write something like this in your stylesheet
tr.filtered {
display: none;
}
Alternative: extend your table body like this:
<tbody>
{% for ad in ads %}
<tr data-ad-id="{{ ad.id }}" class="ad-tr">
<td>{{ ad.departure }}</td>
{# all the other td's #}
</tr>
{% endfor %}
</tbody>
And you Clickhandler:
$('#my_button').click(function() {
//alert(ads);
$.each(ads, function(index, ad) {
if (ad.packageType == 'some_package_type') {
$('table#ads tr[data-ad-id=' + ad.id + ']').hide();
}
});
// rewrite table
// Perhaps there is no need for anymore
});
EDIT:
If you have a javascripts block in your base template, you could do this to expose an ads array to the global JS scope (just like you said in the question, about what you have seen):
{% block javascripts %}
{{ parent() }}
<script>
var ads = {{ ads|json_encode() }};
</script>
{% endblock %}

Categories

Resources