I want to print table row information in a Javascript function bind to the onclick event of a button.
view.py
def table(request):
test_list = TestInformation.objects.order_by()
context = { 'test_list' : test_list, }
return render(request, '/test.html', context)
test.html
<label ~~ id="btn_click" onclick="btn()">
<table class="table table-bordered" id="data_table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{% for li in test_list %}
<tr>
<td> {{ li.Id }} </td>
<td> {{ li.Name}} </td>
</tr>
{% endfor %}
</tbody>
</table>
<Script type="text/javascript">
function btn {
//I'd like to put above {for~~ endfor} source here!
}
</Script>
Currently Action
The table is displayed as soon as you load the html page.
Expected Action
Only visible when the table presses a button
How can I invoke Python objects in JavaScript functions for the actions I expect?
Related
I need to write a compatible algorithm for this code, but I can't. How can I send data to backend?
I am using bootstable.js for table
HTML table:
<table class="table table-bordered" id="table-list">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Slug</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for chart in charts %}
<tr>
<th id="id">{{chart.id}}</th>
<td class="editable" id="name">{{chart.name}}</td>
<td class="editable" id="slug">{{chart.slug}}</td>
<td>john#example.com</td>
</tr>
{% empty %}
<p>No data</p>
{% endfor %}
</tbody>
</table>
And this is my JavaScript code. I tried to try some methods myself but it didn't work
<script src="{% static 'npe_cp/js/bootstable.js' %}"></script>
<script>
//apply
$("#table-list").SetEditable();
$('#addRow').click(function() {
rowAddNew('table-list');
});
$('#bAcep').on('click', function(){
// var id=$("#id").val();
// var name=$("#name-44").val();
// var slug=$("#slug-44").val();
let name=document.querySelector('#name')
console.log(id, name, slug, 'Hello World')
$.ajax({
url:"/chart/edit",
type:"POST",
data:{
"id":id,
"name":name,
"slug":slug,
},
})
});
This is exactly what the table looks like. I want to update, create, and delete operations. But I am not getting the data.
Use Django Forms to populate the database, makes it easy to perform CRUD operations
UPDATE
The solution is in the comments.
Original Post
I have a basic search query to find customers on one of my forms in my Django project. It returns results from the database in an HTML table. The query is executed by clicking the search button. I want to hide the div encapsulating the table when the query has not been executed.
Because the JS function is executed when the search button is clicked, the table only shows momentarily until the page reloads.
What is the convention for displaying a div after a query is executed, without having a constant toggle button?
views.py
#method_decorator(login_required, name='dispatch')
class CustomerResultsView(ListView):
model = CustomerName
template_name = 'parent/child.html'
context_object_name = 'filtered_customers'
#method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['form1'] = FilterForm(initial={
'name': self.request.GET.get('name', ''),
'filter_field': self.request.GET.get('filter_field', '')
})
context['users'] = self.request.user
context['form'] = Customer()
return context
def get_queryset(self):
query = self.request.GET.get('name')
filter_field = self.request.GET.get('filter_field')
if query:
return CustomerName.objects.filter(
Q(('%s__icontains' % filter_field, query))
)
else:
return {}
child.html
<form method="GET">
<legend class="border-bottom mb-4">Customer Lookup</legend>
<fieldset class="form-group">
{{ form1|crispy }}
</fieldset>
<div class="form-group">
<input type="submit" class="btn btn-outline-info mt-4" value="Search" onclick="showDiv()">
</div>
</form>
<hr>
<div class="table-responsive" id="custTabDiv" style="display:none">
<table id="testTable" class="table table-striped table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th class="th-sm" scope="col">First</th>
<th class="th-sm" scope="col">Last</th>
<th class="th-sm" scope="col">Phone</th>
</tr>
</thead>
<tbody>
<tr>
{% for name in filtered_customers %}
<tr>
<td id="test" onclick="customerNameValidation()">{{ name.first_name }}</td>
<td>{{ name.last_name }}</td>
<td>{{ name.phone }}</td>
</tr>
{% endfor %}
</tr>
</tbody>
</table>
<script>
function showDiv() {
document.getElementById("custTabDiv").style.display = "block";
}
</script>
I want to sum up total income and total indirect income. This total values in html table comes using jQuery by providing a class. But now I want to sum up two table total values in a single variable and put in a new html table.
The new html table looks like we have a column total (income+indirect income) = variable. Click to see the HTML table
How can I do that using jQuery. Click this link and see that the values of total amount column are sum up and lies in the footer on every table. But now I want to sum up two table values in a single variable and that new variable I want to put in a new html table on a same page.
$(document).ready(function() {
var total_1 = 0;
$('.income-amount').each(function(i, obj) {
total_1 += parseInt($(obj).text());
});
$('#income-total').text(total_1.toFixed(1));
});
I use this jQuery in the Html table for total amount column sum up.
Below is the html table.
<table id="example" class="table table-striped table-bordered table-responsive-xl">
<caption style="caption-side:top; text-align: center;"><h3>Income</h3></caption>
<thead class="thead-dark">
<tr>
{# <th>S No.</th>#}
<th>Particulars</th>
<th>Description</th>
<th>Total Amount</th>
</tr>
</thead>
<tbody>
{% for item in all_profit %}
{% if item.category.under == "Income" %}
<tr>
{# <td>{{ }} </td>#}
<td>{{item.category}}</td>
<td>{{item.category.desc}}</td>
<td class='income-amount'>{{ item.balance }} </td>
</tr>
{% endif %}
{% endfor %}
</tbody>
<tfoot>
<tr class="totalColumn">
<td style="visibility:hidden;"></td>
<td style="visibility:hidden;"></td>
<td id='income-total'>Total:</td>
</tr>
</tfoot>
</table>
I want to pass the selected radio button value as a parameter with Laravel route.
My Route is:
Route::resource('/datas','DataController');
From this route, I am aiming to call localhost:8000/datas/{data}
My data.blade.php is:
<form id="dataform" action="{{ route('datas.show')}}" method="GET">
<table class="table">
<tr>
<th>Select bullet</th>
<th>SL NO</th>
<th>Name</th>
<th>Age</th>
</tr>
#foreach ($datas $key => $data)
<tr>
<td><input type="radio" id="data{{$data->id}}" name="data" value={{$data->id}}></option></td>
<td>{{$key}}</td>
<td>{{$data->name}}</td>
<td>{{$data->age}}</td>
</tr>
#endforeach
</table>
<button type="submit" id="edit_submit" class="btn btn-default">Show</button> </form>
My show function will be...
public function show($id)
{
//Code to showing data and redirect to show page
}
I want to get value of this radio button(given below).
<td><input type="radio" id="data{{$data->id}}" name="data" value={{$data->id}}>
and include it as a parameter with the Form action below
<form id="dataform" action="{{ route('datas.show')}}" method="GET">
I have made some changes to this code.
Changed button to anchor tag.
So my blade.php is:-
<table class="table">
<tr>
<th>Select bullet</th>
<th>SL NO</th>
<th>Name</th>
<th>Age</th>
</tr>
#foreach ($datas $key => $data)
<tr>
<td><input type="radio" id="data{{$data->id}}" name="data" value={{$data->id}}></option></td>
<td>{{$key}}</td>
<td>{{$data->name}}</td>
<td>{{$data->age}}</td>
</tr>
#endforeach
</table>
Show
and I added a javascript function too.
<script>
function showfunction(){
var id = document.querySelector('input[name = "data"]:checked').value;
var url = '{{route("admin.questions.show",":id")}}';
url=url.replace(':id',id);
document.location.href=url;
}
</script>
You can't accomplish that with just HTML/Blade. You need javascript (or a javascript framework) for the live changes to work since the parameter in your form's action route depends on the value of the selected radio.
action="{{ route('datas.show', [ 'id' => [insert id here] ])}}"
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.