AJAX - Show a <div> on a button click - javascript

As I am implementing AJAX, I would like this whole <div> to show up as a consequence of clicking the button in the script below :
<div class="col-12" id="deleteVote">
<div class="row mb-2" >
<div class="col-12">
{% for vote in proposal.votes %}
{% if app.user == vote.user %}
<a href="{{ path('vote_delete',{'slug' : slug, 'proposal' : proposal.id, 'vote' : vote.id}) }}" class="btn btn-light ml-1 btn-sm deleteVote" data-toggle="deleteConfirmation">
<i class="bi bi-trash"></i> {{ 'vote-delete' | trans }}
</a>
{% endif %}
{% endfor %}
</div>
</div>
</div>
Here is the script, I don't really know why the .show is not working :
<script>
$(document).on('click', '.votedFullAgreement', function (){
$.ajax({
url: '{{ path('vote_add', {'slug' : slug, 'proposal' : proposal.id, 'userVote' : 'votedFullAgreement', 'user' : app.user.id }) }}',
type: 'POST',
dataType: 'html',
success: function (){
$('#deleteVote').show();
},
error: function (resultat, statut, erreur) {
}
});
return false;
});
</script>
Btw the script is probably not optimised at all but it's my first one and it's working and sending data...
Thank you !
EDIT 2 :
I don't understand why this if/else doesn't work. When there's a vote, the if works, the button is there when we come back/reload the page, but when there is no vote yet, the .show(); doesn't activate the else which is in display:none.
Is it because as soon as I vote, the if becomes true? (and .show(); needs something previously hidden to display but can't find any...)
{# Standard loop #}
{% if proposal.votedByUser(app.user) %}
<div class="col-12">
<div class="row mb-2">
<div class="col-12">
{% for vote in proposal.votes %}
{% if app.user == vote.user %}
<a href="{{ path('vote_delete',{'slug' : slug, 'proposal' : proposal.id, 'vote' : vote.id}) }}" class="btn btn-light ml-1 btn-sm" data-toggle="deleteConfirmation">
<i class="bi bi-trash"></i> {{ 'vote-delete' | trans }}
</a>
{% endfor %}
</div>
</div>
</div>
{% else %}
{# AJAX loop #}
<div class="col-12">
<div class="row mb-2">
<div class="col-12">
{% for vote in proposal.votes %}
{% if app.user == vote.user %}
{# ID deleteVote here, which has display:none in the CSS #}
<a href="{{ path('vote_delete',{'slug' : slug, 'proposal' : proposal.id, 'vote' : vote.id}) }}" id="deleteVote" class="btn btn-light ml-1 btn-sm" data-toggle="deleteConfirmation">
<i class="bi bi-trash"></i> {{ 'vote-delete' | trans }}
</a>
{% endif %}
{% endfor %}
</div>
</div>
</div>
{% endif %}
If I split both loops, the AJAX one works only when there is already a vote registered (and the button of the standard loop is already there)

Related

Django and waypoints Infinite scroll not working

I have tried all the answers on stack and the infinite scroll is still not working. My home.html is still displaying the pagination. I suspect the problem is with jquery or the js files or with how the static file is loaded?
Here is my home.html:
{% block content %}
{% load static %}
<div class="infinite-container">
{% for post in posts %}
<div class="infinite-item">
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
</div>
{% endfor %}
</div>
<div class="d-flex d-none position-fixed" style="top:35vh;left:46vw">
<button class="btn btn-primary loading">
<span class="spinner-border spinner-border-sm"></span>
Please wait...
</button>
</div>
<!--pagination logic -->
<div class="col-12">
{% if page_obj.has_next %}
<a class="infinite-more-link" href="?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
</div>
<script src="/static/js/jquery.waypoints.min.js"></script>
<script src="/static/js/infinite.min.js"></script>
<script>
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0],
offset: 'bottom-in-view',
onBeforePageLoad: function () {
$('.loading').show();
},
onAfterPageLoad: function () {
$('.loading').hide();
}
});
</script>
{% endblock content %}
In my settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [Path(BASE_DIR, 'static'),]
The directory of my js files.
I have added the following within my base.html at the bottom.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
here is my class based view in view.py:
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5

best way to store checkbox values in session when paging

I work with Symfony and Twig. I currently have a twig page containing a list of products, I display them with a foreach loop and I put pagination to limit the display of products.
I have a form in this page with a checkbox as input and I need to keep my checkbox checked save in session when I go to the next page
I tried to do it with adding this code
there is some code, I added some comment in the pagination view and controller to explain what I tried.
view of my loop :
<form>
<div class="row" >
{% for annonce in annonces %}
<div class="col-12 col-md-6 col-lg-4">
<p class="text text--blue text--bold m-0 text--medium mt-2">
{{ annonce._source.titre }}
</p>
<p class="m-0">{{ 'Réf' }}: {{ annonce._source.reference }}</p>
<div class="d-flex mt-2 text--bold">
<div class="d-flex me-2">
{{ annonce._source.ville }}
</div>
</div>
<div>
<input type="checkbox" name="checkbox[]" id="checkbox_pdf" value="{{annonce._id}}" multiple/>
</div>
</div>
{% endfor %}
</div>
<input type="submit" id="pdf_submit" value="Create PDF" name="submit_pdf" class="btn btn-primary">
</form>
view of the pagination :
// I tried to add a onclick : onclick='document.forms["name"].submit(); return false;' on each pagination link combined with the save of the value in session with my controller but doesn't work
<div class="col d-flex justify-content-between align-items-center">
<div class="d-flex">
{% if page > 0 %}
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':0, 'type':'frontoffice'}) }}" data-target="pagination-target">
«
</a>
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':page-1, 'type':'frontoffice'}) }}" data-target="pagination-target">
{{ 'Précédent' }}
</a>
{% else %}
<a href="#" disabled="disabled" >
{{ 'Précédent' }}
</a>
{% endif %}
</div>
<div>
<ul class="list-unstyled pagination m-0">
{% for i in (page+1)..(page+4) %}
{% if i <= numberOfMaxPage %}
{% if i == (page+1) %}
<li>
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':(i-1), 'type':'frontoffice'}) }}" data-target="pagination-target">
{{ i }}
</a>
</li>
{% else %}
<li>
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':(i-1), 'type':'frontoffice'}) }}" data-target="pagination-target">
{{ i }}
</a>
</li>
{% endif %}
{% endif %}
{% endfor %}
</ul>
</div>
<div class="d-flex">
{% if page < (numberOfMaxPage-1) %}
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':page+1, 'type':'frontoffice'}) }}" data-target="pagination-target">
{{ 'Suivant' }}
</a>
<a href="#" data-action="pagination" data-uri="{{ path('ajax_annonce_pagination',{'page':numberOfMaxPage-1, 'type':'frontoffice'}) }}" data-target="pagination-target">
»
</a>
{% endif %}
</div>
</div>
JS of the pagination :
$( document ).ready(function() {
$(document).on('click', 'a.pagination',function(e) {
e.preventDefault();
$.ajax({
url: $(this).data('uri'),
}).done(function(html) {
$('#pagination-target').html(html);
$('html,body').animate({scrollTop: $('#pagination-target').offset().top - 80}, 200);
var $scrollable = document.getElementById('pagination-target');
$scrollable.scrollIntoView();
});
});
});
In my controller I render my view like this :
public function search(Request $request, ?SecteurGeographique $secteurGeographique, AnnonceRepository $annonceRepository): Response
{
$selectId = $request->get('checkbox');
$selected = $annonceRepository->findById($selectId);
// I tried to add this code to save my values
if (isset($selectId))
{
$session = new Session();
$session->set('checkbox',$selectId);
}else{
echo 'false';
$session = new Session();
$session->clear();
}
return $this->render('front/annonce/list.html.twig', array(
'annonces' => $results['hits']['hits'],
'total' => $results['hits']['total']['value'],
'website' => $website,
'page' => $request->query->getInt('page')
));
}
It is better to do a save in session my php or in ajax ?
thanks you in advance
Actually, if I understood correctly your code, you don't really need to use session.
I assume that, when you submit the form, then you will need to post all the checkbox value at once to generate your PDF.
If that is try, you should only store the list of the checkboxes directly via Javascript and be sure to send everything when you submit your form.
In this theory, there could be you HTML main page :
<form>
<div class="row" >
{% for annonce in annonces %}
<div class="col-12 col-md-6 col-lg-4">
<p class="text text--blue text--bold m-0 text--medium mt-2">{{ annonce._source.titre }}</p>
<p class="m-0">{{ 'Réf' }}: {{ annonce._source.reference }}</p>
<div class="d-flex mt-2 text--bold">
<div class="d-flex me-2">
{{ annonce._source.ville }}
</div>
</div>
<p>
<input type="checkbox" name="checkbox[]" class="checkboxPDF" value="{{annonce._id}}"/>
</div>
{% endfor %}
</div>
<div id="savedCheckboxes" class="d-none"></div>
<input type="submit" id="pdf_submit" value="Create PDF" name="submit_pdf" class="btn btn-primary">
</form>
Here, you can see that I added the invisible div #savedCheckboxes. That will allow us to save all the checkboxes when you change your pages. I also corrected a little bit your HTML, but nothing major.
Then you should update your pagination javascript :
$(document).ready(function() {
$(document).on('click', 'a.pagination',function(e) {
e.preventDefault();
// Save all the selected checkboxes by moving them to #savedCheckboxes
$('.checkboxPDF:checked').appendTo($('#savedCheckboxes'))
// Do your pagination like you did
$.ajax({
url: $(this).data('uri'),
}).done(function(html) {
$('#pagination-target').html(html);
// If the user come to a previous page, verify if he did selected a checkbox
$('#pagination-target .checkboxPDF').each(function(i, element) {
// If the checkbox already exists in the #savedCheckboxes, then select this checkBox & remove it from #savedCheckboxes
var savedCheckbox = $('#savedCheckboxes .checkboxPDF[value="'+element.val()+'"]')
if(savedCheckbox.length > 0) {
element.click() // Select this checkbox
savedCheckbox.remove() // Remove it from the hidden selection
}
})
$('html,body').animate({scrollTop: $('#pagination-target').offset().top - 80}, 200);
var $scrollable = document.getElementById('pagination-target');
$scrollable.scrollIntoView();
});
});
});
And the magic is done ... When you will submit your form, you will always receive ALL the list of the selected Checkbox, even those that are not displayed anymore because of your pagination.

Shopify Store Refresh cart content. AJAX request

I have product page on which I have shop now btn. When user clicks on this button, page opens cart drawer with custom ajax template content.
I rewrited click event with my own logic. I use AJAX and send request for adding product by myself. Products are adding but is not showing in the cart drawer. Only after reloading page it is appearing.
Question is to can I refresh cart content? I'm trying to past content template via inner html. But it is looks like not liquid format.
Here is the template
<script id="CartTemplate" type="text/template">
{% render 'banana-stand-cart-top-container' %}
{% raw %}
<div class="drawer__scrollable">
{{#items}}
<div class="ajaxcart__product appear-animation appear-delay-{{animationRow}}">
<div class="ajaxcart__row">
<div class="grid">
<div class="grid__item one-third">
<img src="{{img}}" alt="{{name}}">
</div>
<div class="grid__item two-thirds">
<div class="ajaxcart__product-name--wrapper">
{{{name}}}
{{#if variation}}
<div class="ajaxcart__product-meta">{{variation}}</div>
{{/if}}
{{#if selling_plan_name}}
<div class="ajaxcart__product-meta">{{selling_plan_name}}</div>
{{/if}}
{{#properties}}
{{#each this}}
{{#if this}}
<span class="ajaxcart__product-meta">{{#key}}: {{this}}</span>
{{/if}}
{{/each}}
{{/properties}}
</div>
<div class="grid grid--full display-table">
<div class="grid__item display-table-cell one-half">
<label for="updates_{{key}}" class="visually-hidden">{% endraw %}{{ 'products.product.quantity' | t }}{% raw %}</label>
<div class="js-qty__wrapper">
<input type="text" id="updates_{{key}}"
class="js-qty__num"
value="{{itemQty}}"
data-id="{{key}}"
min="0"
aria-label="quantity"
pattern="[0-9]*"
name="updates[]">
<button type="button"
class="js-qty__adjust js-qty__adjust--minus"
aria-label="{% endraw %}{{ 'cart.general.reduce_quantity' | t }}{% raw %}">
{% endraw %}<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon-minus" viewBox="0 0 20 20"><path fill="#444" d="M17.543 11.029H2.1A1.032 1.032 0 0 1 1.071 10c0-.566.463-1.029 1.029-1.029h15.443c.566 0 1.029.463 1.029 1.029 0 .566-.463 1.029-1.029 1.029z"/></svg>{% raw %}
<span class="icon__fallback-text" aria-hidden="true">−</span>
</button>
<button type="button"
class="js-qty__adjust js-qty__adjust--plus"
aria-label="{% endraw %}{{ 'cart.general.increase_quantity' | t }}{% raw %}">
{% endraw %}<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon-plus" viewBox="0 0 20 20"><path fill="#444" d="M17.409 8.929h-6.695V2.258c0-.566-.506-1.029-1.071-1.029s-1.071.463-1.071 1.029v6.671H1.967C1.401 8.929.938 9.435.938 10s.463 1.071 1.029 1.071h6.605V17.7c0 .566.506 1.029 1.071 1.029s1.071-.463 1.071-1.029v-6.629h6.695c.566 0 1.029-.506 1.029-1.071s-.463-1.071-1.029-1.071z"/></svg>{% raw %}
<span class="icon__fallback-text" aria-hidden="true">+</span>
</button>
</div>
</div>
<div class="grid__item display-table-cell one-half text-right">
{{#if discountsApplied}}
<small class="cart__price--strikethrough">{{{price}}}</small>
<span class="ajaxcart__price">
{{{discountedPrice}}}
</span>
{{else}}
<span class="ajaxcart__price">
{{{price}}}
</span>
{{/if}}
</div>
</div>
<div class="grid grid--full display-table">
{{#if discountsApplied}}
<div class="grid__item text-right">
{{#each discounts}}
<small class="ajaxcart__discount cart__discount">
{{this.discount_application.title}} (-{{{this.formattedAmount}}})
</small>
{{/each}}
</div>
{{/if}}
{{#if unitBase}}
<div class="grid__item text-right">
<div class="product__unit-price">
{{{ unitPrice }}}/{{{ unitBase }}}
</div>
</div>
{{/if}}
</div>
</div>
</div>
</div>
</div>
{{/items}}
{% endraw %}{% if settings.cart_notes_enable %}{% raw %}
<div class="appear-animation appear-delay-{{lastAnimationRow}}">
<label for="CartSpecialInstructions" class="ajaxcart__note">{% endraw %}{{ 'cart.general.note' | t }}{% raw %}</label>
<textarea name="note" class="input-full cart-notes" id="CartSpecialInstructions">{{note}}</textarea>
</div>
{% endraw %}{% endif %}{% raw %}
</div>
<div class="drawer__footer appear-animation appear-delay-{{lastAnimationRow}}">
{{#if cartDiscounts }}
<div class="grid grid--full">
<div class="grid__item one-half">
<p class="ajaxcart__subtotal">{% endraw %}{{ 'cart.general.discounts' | t }}{% raw %}</p>
</div>
<div class="grid__item one-half text-right">
{{#each cartDiscounts}}
<p class="ajaxcart__price cart__discount">
{{this.title}} (-{{{this.formattedAmount}}})
</p>
{{/each}}
</div>
</div>
{{/if}}
<div class="grid grid--full">
<div class="grid__item one-half">
<p class="ajaxcart__subtotal">{% endraw %}{{ 'cart.general.subtotal' | t }}{% raw %}</p>
</div>
<div class="grid__item one-half text-right">
<p class="ajaxcart__price"><span class="tdf-cart-total-parent">{{totalPrice}}</span></p>
</div>
</div>
<p class="ajaxcart__note">
{% endraw %}{{ 'cart.general.shipping_at_checkout' | t }}{% raw %}
</p>
{% endraw %}{% if settings.cart_terms_conditions_enable %}
<p class="ajaxcart__note ajaxcart__note--terms">
<input type="checkbox" id="CartAgree" />
<label for="CartAgree">
{% if settings.cart_terms_conditions_link != blank %}
{{ 'cart.general.terms_html' | t: url: settings.cart_terms_conditions_link }}
{% else %}
{{ 'cart.general.terms' | t }}
{% endif %}
</label>
</p>
{% endif %}{% raw %}
{% endraw %}
{% if additional_checkout_buttons and settings.cart_additional_buttons %}
<div class="additional-checkout-buttons additional-checkout-buttons--vertical">{{ content_for_additional_checkout_buttons }}</div>
{% endif %}
{% raw %}
<button type="submit" class="btn btn--full cart__checkout{% endraw %}{% if settings.cart_terms_conditions_enable %}{% raw %} cart__checkout--ajax{% endraw %}{% endif %}{% raw %}" name="checkout">
{% endraw %}{{ 'cart.general.checkout' | t }}{% raw %}
</button>
</div>
{% endraw %}
Usually, there is some way (js-function) that allows you to rebuild the cart with new items.
You need to check the js-code that is responsible for showing the drawer-cart
So, need fire some event that you can find in your theme.js file. In my case I needed to add this:
document.dispatchEvent(new CustomEvent('cart:build', {
detail: {
cart: cart
}
}));

how to increment a like button in django with ajax?

i have a post in a community and i have implemented the like button in django + ajax but i notice that when i do like a post it increments all the post's likes.how can i solve it ?
here is my template:
{% for post in posts %}
<div class="w3-container w3-card w3-white w3-round">
<a target="_blank" href="{{ post.author.profile.avatar.url }}">
<img src="{{ post.author.profile.avatar.url }}" alt="Avatar" class="w3-left w3-circle w3-margin-right" style="width:60px"></a>
<h4>
<a href ='{% url 'profile' post.author.pk %}'>{{ post.author.profile.prenom|title }} {{ post.author.profile.nom|title }}</a>
</h4>
<span class="w3-opacity">{{ post.created|date:"d-m-Y H:i" }}</span>
<br>
<hr class="w3-clear">
<p>
{{ post.contenu }}</p>
<button type="button" class="btn btn-default btn-sm">
{{ post.comment_set.count }} </span>
</button>
{% if request.user in post.liked.all %}
<button type="button" class="btn btn-default btn-sm">
<span class='like_count'>{{ post.liked.count }} </span><a name="{{ post.id }}" style="color: blue;" class="likin" id="co"><span class="glyphicon glyphicon-heart"></span> j'aime</a>
</button>
{% else %}
<button type="button" class="btn btn-default btn-sm">
<span class='like_count'>{{ post.liked.count }} </span><a name="{{ post.id }}" style="color: black;" class="likin" id="co"><span class="glyphicon glyphicon-heart"></span> j'aime</a>
</button>
{% endif %}
{% if request.user == post.author %}
<button type="button" class="btn btn-default btn-sm">
</span>
</button>
{% endif %}
<br>
<br>
</div>
<br>
{% empty %}
<span class='w3-opacity'>Aucun post dans cette communaute</span>
<br>
<br>
{% endfor %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// AJAX CALL
$('.likin').click(function(){
$.ajax({
type: "POST",
url: "{% url 'like_community' %}",
data: {'content_id': $(this).attr('name'),'operation':'like_submit','csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response) {
selector = document.getElementsByName(response.content_id);
if(response.liked==true){
$(selector).css("color","blue");
$('.like_count').html(response.likes_count);
}
else if(response.liked==false){
$(selector).css("color","black");
$('.like_count').html(response.likes_count);
}
}
});
})
</script>
this is my views.py with the part ajax like:
def like_community(request):
if request.method =="POST":
if request.POST.get("operation") == "like_submit" and request.is_ajax():
content_id=request.POST.get("content_id",None)
content=get_object_or_404(Post,pk=content_id)
if content.liked.filter(id=request.user.id): #already liked the content
content.liked.remove(request.user) #remove user from likes
liked=False
else:
content.liked.add(request.user)
liked=True
ctx={"likes_count":content.liked.count() ,"liked":liked,"content_id":content_id}
return HttpResponse(json.dumps(ctx), content_type='application/json')
i really need a help.i am new in ajax and i just find a tutorial online and i follow but the implementation of count_like button was not there.i will appreciate any help.Merci.
You seem to have non-unique ID of "co" - Then you use the wrong method document.getElementsByName which returns a collection of NAMED elements but you pass it response.content_id
Also you use $('#response.content_id') which will look for an element with `id="response.content_id"
Change to
$('.likin').click(function(e){
e.preventDefault; // stop the link
$liked = $(this); // the link clicked
$.ajax({
success: function(response) {
$liked.prev().html(response.likes_count); // the span before the "likin"
$liked.css("color",response.liked==true ? "blue": "black");
}

Adding Django MultipleChoiceField one after the other using Javascript

I am working on a Django views based on the following form:
class MyForm(forms.Form):
def __init__(self, data, examen, *args, **kwargs):
super(MyForm, self).__init__(data, *args, **kwargs)
self.fields['q1'] = forms.MultipleChoiceField(
label=mark_safe("Label question 1"),
required=True,
widget=forms.CheckboxSelectMultiple,
choices=(('1', 'answer 1'), ('2', 'answer 2'), ('3', 'answer 3'))
)
self.fields['q2'] = forms.MultipleChoiceField(
label=mark_safe("Label question 2"),
required=True,
widget=forms.CheckboxSelectMultiple,
choices=(('1', 'answer 4'), ('2', 'answer 5'), ('3', 'answer 6'))
)
... #TODO : add questions q3 to q9
self.fields['q10'] = forms.MultipleChoiceField(
label=mark_safe("Label question 10"),
required=True,
widget=forms.CheckboxSelectMultiple,
choices=(('1', 'answer 28'), ('2', 'answer 29'), ('3', 'answer 30'))
)
Il would like to display on a single view self.fields['q1'] with a [submit] button. The idea is for the user to select the answer he considers as correct and the hit the [submit] button. Following that self.fields['q1'] will turn into read-only and self.fields['q2'] will display just below with again a [submit] button... and son on until self.fields['q10'].
I do believe that the only way to achieve that is to use Javascript (and even JQuery or any other library). The problem is that I'm not very familiar with Javascript and would gladly appreciate hints on how to tackle that issue.
Thank you for what you can do!
PS: I'm happy to change my Django design if you think this is not the proper way to achieve my goal.
EDIT 29/11/2019: my current template looks like:
<form action="{% url 'quizz' my_exam %}" method="post">
{% csrf_token %}
{% for field in form %}
{% ifequal forloop.counter0 0 %}
<div class="card text-white bg-primary mb-3">
<div class="card-body">
<h6 class="card-title">{{ field.label|linebreaksbr }}</h6>
</div>
</div>
{% else %}
<div class="card">
<h5 class="card-header">{{field.name}}</h5>
<div class="card-body">
<h6 class="card-title">{{ field.label|linebreaksbr }}</h6>
<p class="card-text">{{ field }}</p>
</div>
</div>
{% endifequal %}
{% endfor %}
<input type="submit" value="Submit" class="btn btn-primary"/>
</form>
EDIT 30/11/2019: new template based on #Phanti suggestions:
<script>
{% block jquery %}
$("#submit_2").click(function() {
$("#questions_container").find(":hidden").show().next();
}
{% endblock %}
</script>
{% block content %}
<form action="{% url 'quizz' exam %}" method="post">
{% csrf_token %}
<div id="questions_container">
{% for field in form %}
{% ifequal forloop.counter 1 %}
<div class="card text-white bg-primary mb-3">
<div class="card-body">
<h6 class="card-title">{{ field.label|linebreaksbr }}</h6>
</div>
</div>
{% else %}
{% ifequal forloop.counter 2 %}
<div id="question_{{ forloop.counter }}" class="card" style="display: block;">
<h5 class="card-header">{{field.name}}</h5>
<div class="card-body">
<h6 class="card-title">{{ field.label|linebreaksbr }}</h6>
<p class="card-text">{{ field }}</p>
</div>
</div>
<input id="submit_{{ forloop.counter }}" value="Valider" class="btn btn-primary" style="display: block;"/>
{% else %}
<div id="question_{{ forloop.counter }}" class="card" style="display: none;">
<h5 class="card-header">{{field.name}}</h5>
<div class="card-body">
<h6 class="card-title">{{ field.label|linebreaksbr }}</h6>
<p class="card-text">{{ field }}</p>
</div>
</div>
{% if not forloop.last %}
<input id="submit_{{ forloop.counter }}" value="Submit" class="btn btn-primary" style="display: none;"/>
{% else %}
<input id="submit_{{ forloop.counter }}" type="submit" value="Submit" class="btn btn-primary" style="display: none;"/>
{% endif %}
{% endifequal %}
{% endifequal %}
{% endfor %}
</div>
</form>
{% endblock %}

Categories