I'm trying to send an array of row id's to a controller in order to do a batch update, I think I already did the array part (i'm not good at jQuery, still learning) but I have no idea how to send to the controller the array that contains the ids of the rows to update.
Here's my twig:
{% block javascripts %}
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$('#selectall').click(function () {
$('.selectedId').prop('checked', isChecked('selectall'));
});
});
function isChecked(checkboxId) {
var id = '#' + checkboxId;
return $(id).is(":checked");
}
function resetSelectAll(id) {
// if all checkbox are selected, check the selectall checkbox
// and viceversa
if ($(".selectedId").length == $(".selectedId:checked").length) {
$("#selectall").attr("checked", "checked");
var ids = [];
ids.concat(id);
} else {
$("#selectall").removeAttr("checked");
removeItem = id;
ids = jQuery.grep(arr, function(value) {
return value != removeItem;
});
}
if ($(".selectedId:checked").length > 0) {
$('#edit').attr("disabled", false);
} else {
$('#edit').attr("disabled", true);
}
}
</script>
{% endblock %}
{% block body %}
<table>
<thead>
<tr>
<th><input type="checkbox" id="selectall"></th>
<th>{{ 'general.date'|trans }}</th>
<th>{{ 'general.order_number'|trans }}</th>
<th>{{ 'general.description'|trans }}</th>
<th>{{ 'general.company_name'|trans }}</th>
<th>{{ 'general.name'|trans }}</th>
<th>{{ 'form.status'|trans }}</th>
<th>WinPoints</th>
</tr>
</thead>
{% for details in details %}
<tbody>
<tr>
<td><div align="center"><input type="checkbox" class="selectedId" name="selectedId" onclick="resetSelectAll({{details.id}});" /></div></td>
<td>{{ details.date | date("m/d/Y") }}</td>
<td>{{ details.order_number }}</td>
<td>{{ details.description }}</td>
<td>{{ details.company }}</td>
<td>{{ details.name }}</td>
<td>{{ details.status }}</td>
<td>{{ details.winpoints }}</td>
</tr>
</tbody>
{% endfor %}
</table>
<form action="{{ path('advd_group_batch_p_r_status') }}" method="post" {{ form_enctype(formBase) }}>
{{ form_widget(form) }}
<input class="input_button" type="submit" value="Procesar" />
</form>
{% endblock %}
Any ideas? Plus, if you see any mistakes on the jquery code, please let me know what i'm doing wrong, i haven't been able to test it because I don't know how to send the array to the controller.
Thank you for any help you may offer me.
{% block javascripts %}
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$('#selectall').click(function () {
$('.selectedId').prop('checked', isChecked('selectall'));
});
});
function isChecked(checkboxId) {
var id = '#' + checkboxId;
return $(id).is(":checked");
}
function resetSelectAll(id) {
// if all checkbox are selected, check the selectall checkbox
// and viceversa
if ($(".selectedId").length == $(".selectedId:checked").length) {
$("#selectall").attr("checked", "checked");
var ids = [];
ids.concat(id);
} else {
$("#selectall").removeAttr("checked");
removeItem = id;
ids = jQuery.grep(arr, function(value) {
return value != removeItem;
});
}
if ($(".selectedId:checked").length > 0) {
$('#edit').attr("disabled", false);
} else {
$('#edit').attr("disabled", true);
}
}
$(function(){
$('.input_button').click(function(){
$.ajax({
url:"advd_group_batch_p_r_status",
dataType:'json',
type:'post',
data:$("#formC").serialize()
});
});
});
</script>
{% endblock %}
{% block body %}
<form action="{{ path('advd_group_batch_p_r_status') }}" method="post" {{ form_enctype(formBase) }} id="formC">
<table>
<thead>
<tr>
<th><input type="checkbox" id="selectall"></th>
<th>{{ 'general.date'|trans }}</th>
<th>{{ 'general.order_number'|trans }}</th>
<th>{{ 'general.description'|trans }}</th>
<th>{{ 'general.company_name'|trans }}</th>
<th>{{ 'general.name'|trans }}</th>
<th>{{ 'form.status'|trans }}</th>
<th>WinPoints</th>
</tr>
</thead>
{% for details in details %}
<tbody>
<tr>
<td><div align="center"><input type="checkbox" class="selectedId" name="selectedId" onclick="resetSelectAll({{details.id}});" /></div></td>
<td>{{ details.date | date("m/d/Y") }}</td>
<td>{{ details.order_number }}</td>
<td>{{ details.description }}</td>
<td>{{ details.company }}</td>
<td>{{ details.name }}</td>
<td>{{ details.status }}</td>
<td>{{ details.winpoints }}</td>
</tr>
</tbody>
{% endfor %}
</table>
{{ form_widget(form) }}
<input class="input_button" type="submit" value="Procesar" />
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
I have a Newsletter form in my application that is posted with the following javascript:
<script type="text/javascript">
function subscribeButtonPressed() {
$.post('{{path('mailchimp_subscribe')}}',
{
EMAIL: $("#mce-EMAIL").val(),
listid: $("#listid").val()
},
function (response) {
ga('send', 'pageview', '{{ path('mailchimp_subscribe') }}');
console.log(response);
if (response.code == 100 && response.success) {//dummy check
var alert = '<div class="span12 padding20" id="formContainer">\n\
<h1>Great!</h1>\n\
</div>';
$('#formContainer').fadeOut('slow', function () {
$('#thanksContainer').append(alert).hide().fadeIn('slow');
});
}
}, 'JSON');
}
$(document).ready(function () {
$('#mc-embedded-subscribe')
.click(function (event) {
var btn = $(this);
if ($("#mce-EMAIL").val() != "") {
event.preventDefault();
btn.button('loading');
subscribeButtonPressed();
}
});
});
</script>
I also log the event via google analytics and show some response html. But I guess you get the idea, just use $.post with the path where you want to send it to. And I pick the single values of my form, but you could also just send the whole form.
Related
I have a model form that I am displaying in a table. The form has about 40 fields broken down into 6 different tables. I have setup an if statements to not display the table elements if the field is empty in the db. This works as expected the only issue is that if all the elements are hidden the table header is still displayed. How could I hide the table header if all if the elements in that particular table are hidden.
<table class="post-table">
<tr>
<th class="table-header" colspan="2">
<h3>Pool Details</h3>
</th>
</tr>
<tbody>
{% if post.pool_size != '' %}
<tr>
<td>pool size:</td>
<td>{{ post.pool_size }}</td>
</tr>
{% endif %}
{% if post.pool_style != '' %}
<tr>
<td>Pool Style:</td>
<td>{{ post.pool_style }}</td>
</tr>
{% endif %}
</tbody>
</table>
Update:
<table class="post-table">
<tr>
<th class="table-header" COLSPAN="1" id="tab_header">
<H3>ADDITIONAL INFO</H3>
</th>
</tr>
<tbody id="tab_body">
{% if post.additional_info != '' %}
<tr>
<td>{{ post.additional_info }}</td>
</tr>
{% endif %}
</tbody>
</table>
<br>
<script>
let tbody = document.getElementById("tab_body").innerHTML;
if (tbody === '') {
tab_header = document.getElementById("tab_header").innerHTML = " ";
} else {
// Nothing to do i guess
}
</script>
You can use JavaScript to hide the header if the <tbody> is empty :
Suppose that we have <th id="tab_header">Tab header</th> <tbody id="tab_body">Some content here</tbody>
Then
let tbody = document.getElementById("tab_body").innerHTML;
# Check if it contains something
if (tbody === '') {
tab_header = document.getElementById("tab_header").innerHTML = "";
} else {
// Nothing to do i guess
}
NB Be aware about checking the content of may be it is not empty string but sme other thing else.
<table class="post-table" id="table-example">
<tr>
<th class="table-header" COLSPAN="1" id="tab_header">
<H3>ADDITIONAL INFO</H3>
</th>
</tr>
<tbody id="tab_body">
{% if post.additional_info != '' %}
<tr>
<td id="test">{{ post.additional_info }}</td>
</tr>
{% endif %}
</tbody>
</table>
<script>
var tbl = document.getElementById('table-example');
if (tbl.rows.length == 1) {
console.log('IT WORKED')
tab_header = document.getElementById("tab_header").innerHTML = "";
}
console.log(tbl.rows.length)
</script>
I'm using a datatable in Bootstrap to create a table which jinja2 will populate with values passed from Flask, example below:
Name
URL
google
www.google.com
reddit
www.reddit.com
{% for site in results %}
<tr>
<td>{{ site['sitename'] }}</td>
<td>{{ site['url'] }}</td>
</tr>
{% endfor %}
I also have site['new_url'] which is passed in results. I want to make the site['url'] clickable and have that toggle between site['url'] and site['new_url'] when clicked.
I'd like to implement using JS if possible or if there is another easier way I'm up for that too!
Any help is appreciated!
A Js solution:
{% for site in results %}
<tr>
<td>{{ site['sitename'] }}</td>
<td onclick="swapText()" id="target">{{ site['url'] }}</td>
</tr>
<script>
function swapText() {
var x = document.getElementById("target");
if (x.innerHTML === "{{ site['url'] }}") {
x.innerHTML = "{{ site['new_url'] }}";
} else {
x.innerHTML = "{{ site['url'] }}";
}
}
</script>
{% endfor %}
My script successfully shows and hides a column in the table, I would like by default for it to be hidden and the script to reveal it.
Thanks for your help.
<a onclick="myFunction()" style="float:right;">Hide/Show</a>
<table>
<tr>
<th>TO Date</th>
<th id="myDIV">LDG Date</th>
<th>TO Time</th>
<th>LDG Time</th>
<th>Dep. air.</th>
<th>Arr. air.</th>
<th></th>
</tr>
{% for l in logbook %}
<tr>
<td>{{ l.TO_Date }}</td>
<td id="myDIV">{{ l.LDG_Date }}</td>
<td>{{ l.TO_time }}</td>
<td>{{ l.LDG_time }}</td>
<td>{{ l.dep_airport }}</td>
<td>{{ l.arr_airport }}</td>
<td ><a style="color:red;" href="{{ url_for('logbookdelete',id_del=l.id ) }}">Delete</a></td>
</tr>
{% endfor %}
</table>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "block") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Just add style="display: none;" to your cells:
<th class="myDIV" style="display: none;">
Notice I've changed id to class as you are not supposed to have two equal id's on the same page.
But I'd do that this way:
<style>
.ldg-date-hidden .myDIV { display: none; }
</style>
<a onclick="myFunction()" style="float:right;">Hide/Show</a>
<table id="myTable" class="ldg-date-hidden">
<tr>
<th>TO Date</th>
<th class="myDIV">LDG Date</th>
<th>TO Time</th>
<th>LDG Time</th>
<th>Dep. air.</th>
<th>Arr. air.</th>
<th></th>
</tr>
{% for l in logbook %}
<tr>
<td>{{ l.TO_Date }}</td>
<td class="myDIV">{{ l.LDG_Date }}</td>
<td>{{ l.TO_time }}</td>
<td>{{ l.LDG_time }}</td>
<td>{{ l.dep_airport }}</td>
<td>{{ l.arr_airport }}</td>
<td ><a style="color:red;" href="{{ url_for('logbookdelete',id_del=l.id ) }}">Delete</a></td>
</tr>
{% endfor %}
</table>
<script>
function myFunction() {
document.getElementById("myTable").classList.toggle("ldg-date-hidden");
}
</script>
You can hide the column by setting display:none by default and then you can do the below:
function myFunction() {
var x = document.getElementsByClassName("myDIV");
for(var i=0;i<x.length;i++)
{
if (x[i].style.display === "block") {
x[i].style.display = "block";
} else {
x[i].style.display = "none";
}
}
}
You can force the initial state by putting the inline style (display:none) on the tag, its not the best way but that should work.
I recommend you to make the styles on a css file separated of the html file to avoid hierarchy issues.
const x = document.getElementById('myDIV');
function toggleVisibility() {
if (x.classList.contains('hidden')) {
x.classList.remove('hidden');
} else {
x.classList.add('hidden');
}
}
CSS file
.hidden: {
display: none;
}
I have a model named Actie in models.py.
The context I passed: {'actie': Actie.objects.all(), 'user': request.user}
This is my template I rendered by a view:
{% for actie in actie %}
{% if actie.actie_gebruiker.id == user.id %}
<tr onclick="window.location.href={{ actie.id }}">
<td>{{ actie.id }}</td>
<td>{{ actie.actie_naam }}</td>
<td>{{ actie.actie_status.status_naam }}</td>
<td>{{ actie.actie_aanmaakdatum|date:"d-m-y [ H:i ]" }}</td>
<td>{{ actie.actie_einddatum|date:"d-m-y" }}</td>
<td>{{ actie.actie_eindtijdstip|date:"[ H:i ]" }}</td>
<td>{{ actie.actie_gebruiker }}</td>
</tr>
<a id="verwijderenButton" href="" onclick="bevestigVerwijdering({{ actie_id }});"><img class="icontje"
src="{% static 'MyApp/verwijderen.png' %}"></a>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
<script>
function bevestigVerwijdering(id) {
var actie_id = '{{ actie.id }}';
var antwoord = confirm("Weet u zeker dat u deze actie wilt verwijderen?");
if (antwoord == true) {
document.getElementById('verwijderenButton').href = 'verwijderen/' + id + '/';
alert(id);
alert(document.getElementById('verwijderenButton').href);
//window.location.href= 'verwijderen/' + id + '/';
}
}
</script>
Now what I want this code to do is that when I click on the image, that it deletes that specifc record out of the database.
It deletes nothing when I don't click on the first record but deletes the last record when I click on the first record.
This is my view:
def verwijderActie(request, id):
Actie.objects.filter(id=id).delete()
return HttpResponseRedirect('../../')
You are creating a list of elements with the same id, then, when you call the javascript function, it gets the first element with the called id.
I would make something like that:
{% for actie in actie %}
{% if actie.actie_gebruiker.id == user.id %}
<tr onclick="window.location.href={{ actie.id }}">
<td>{{ actie.id }}</td>
<td>{{ actie.actie_naam }}</td>
<td>{{ actie.actie_status.status_naam }}</td>
<td>{{ actie.actie_aanmaakdatum|date:"d-m-y [ H:i ]" }}</td>
<td>{{ actie.actie_einddatum|date:"d-m-y" }}</td>
<td>{{ actie.actie_eindtijdstip|date:"[ H:i ]" }}</td>
<td>{{ actie.actie_gebruiker }}</td>
</tr>
<a id="verwijderenButton_{{ actie.id }}" href="#" onclick="bevestigVerwijdering({{ actie.id }});return false;"><img class="icontje" src="{% static 'MyApp/verwijderen.png' %}"></a>
{% endif %}
{% endfor %}
<script>
function bevestigVerwijdering(id) {
var actie_id = id;
var antwoord = confirm("Weet u zeker dat u deze actie wilt verwijderen?");
if (antwoord == true) {
document.getElementById('verwijderenButton_'+id).href = 'verwijderen/' + id + '/';
alert(id);
alert(document.getElementById('verwijderenButton').href);
//window.location.href= 'verwijderen/' + id + '/';
}
}
</script>
i have table render with PHP using foreach loop.
#foreach ($comments as $comment)
<tr>
<td>{{ $comment->lot_date }}
<br>
#if (count($comment->ourcar) >= 1)
<p>Saved</p>
#else
<form method="POST" action="/comments/{{ $comment->id }}/ourcars">
{{ csrf_field() }}
<button type="submit" class="btn btn-xs btn-primary">Our Car</button>
</form>
#endif
</td>
<td>
{{ $comment->bid }}
</td>
<td>{{ $comment->auction_name }}</td>
<td class="block">
#foreach(explode('#', $comment->pics_urls, 3) as $pic)
<a href="{{ $pic }}" class='iframe'>
<img src="{{ $pic }}" class="img-fluid" width="30" height="32">
</a>
#endforeach
</td>
<td>{{ $comment->company }}</td>
<td>{{ $comment->model_name_en }}</td>
<td>{{ $comment->model_type_en }}</td>
<td>{{ $comment->grade_en }}</td>
<td>{{ $comment->model_year_en }}</td>
<td>{{ $comment->color_en}}</td>
<td>{{ $comment->displacement }}</td>
<td>{{ $comment->transmission_en }}</td>
<td>{{ $comment->scores_en }}</td>
<td>{{ $comment->mileage_num }}</td>
<td>{{ $comment->start_price_en }}</td>
<td><div class="comment-body">{{ $comment->body }}</div></td>
<td>{{ $comment->lot->result_en or '---' }}</td>
<td>{{ $comment->user->name }}
<td>
<button data-id="{{ $comment->id }}" class="btn-link editButton"><span class='glyphicon glyphicon-edit'></span></button>
</td>
<td>
<form method="POST" action="{{route('comments.destroy', ['id' => $comment->id]) }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<div class="form-group">
<button type="submit" class="btn-link" onclick="return confirm('Are you sure?')"><span class='glyphicon glyphicon-trash' style="color:red"></span></button>
</div>
</form>
</td>
</tr>
#endforeach
I create a modal window to add comment to the row using JS. After i submit comment and modal is closed and i want to refresh content in <td class="comment-body">comment</td>
So i have a problem with refreshing div by class, i can use an id because table is looped:
$(function() {
$('.editButton').click(function (e) {
var button = $(this);
var geturl = '/comments/' + button.data('id') + '/edit';
var posturl = '/comments/' + button.data('id');
$.get(geturl)
.done( (response) => {
bootbox.dialog( {
title : "Add comment",
message : response,
buttons : {
addButton : {
label : 'Add comment',
className : 'btn btn-primary',
callback: () => {
var modalForm = $('#modalForm');
if ($('#commentBody').val()) {
$.ajax({
type : 'POST',
url : posturl,
data : modalForm.serialize(),
success : (response) => {
if (response === "ok") {
bootbox.hideAll();
$('.comment-body').toggle();
}
}
})
}
return false;
}
},
closeButton : {
label : 'Close',
className : 'btn btn-default'
}
}
})
})
.fail( ( errorResponse ) => {
bootbox.alert('Error! Comment is not added');
});
});
});
</script>
My modal view:
<div class="modal-body">
<form action="#" id="modalForm" data-id="{{ $comment->id }}">
<div class="form-group">
{{ csrf_field() }}
{{ method_field('PUT') }}
<textarea name="body" id="commentBody"
placeholder="Add Your Comment Here." class="form-control" required>{{ $comment->body }}</textarea>
</div>
</form>
</div>
This is the result:
I tried to use $('.comment-body').toggle(); but it is not working. How should i refresh that div after editing comment?
If I got your point .. I think its very simple
1st: you need to use after var button = $(this);
var comment_section = button.closest('tr').find('.comment-body');
2nd: on ajax success callback function
comment_section.text($('#commentBody').val());
var old_comment = $('.comment-body').text();
$('.comment-body').text(old_comment + '\n' + new_comment);
I don't really understand about your refresh. The code above is to append a new comment to old ones.
Set the innerHTML of the element to populate it, or use empty string to clear it:
$('.comment-body').html("New Comment") // New contents
$('.comment-body').html("") // Clear contents
If you have a .comment-body in more than one row of your table, and you only want to "refresh" one of them, then you'll need to specify an id so you can pinpoint the row that contains the cell. E.g...
<tr id="row1"><td class="comment-body">..comment..</td><tr>
$("#row1").find(".comment-body").html("New Comment Text")
NB: Instead of .html you may also use .text to prevent html code in users' comments from being injected into your page.
$('.comment-body').('');
Try this or
$('.comment-body').html('');