I've been trying to create a popup delete confirmation overlay from a forloop. I can't make it work or define which ids or how to pass identifiers for the overlay.
I got this, but it only refers the first element of the loop. I tried serialize the ids with the element pk (myNavRef{{ref.pk}}), but doesn't work
{% for ref in perf_bim.referenciapredio_set.all %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<th>{{ref.rol_fk.rol}}</th>
<th>{{ref.rol_fk.dir}}</th>
<td><img src="{% static 'arrow.png' %}" height=20 alt=""></td>
<td><button onclick="openNavRef()" type="button" class="btn btn-outline-dark btn-sm"><img src="{% static 'trash.svg' %}" alt="" height=15 ></button><br></td>
</tr>
<div id="myNavRef" class="overlay">
<div class="fontformat"style="padding-top:250px;width:40%;margin:auto;">
<div class="overlay-content">
Eliminar Referncia de Predio Rol: {{ref.rol_fk.rol}}
<br>
Cancelar
</div>
</div>
</div>
{% endfor %}
<script>
function openNavRef() {
document.getElementById("myNavRef").style.display = "block";
}
function closeNavRef() {
document.getElementById("myNavRef").style.display = "none";
}
</script>
thanks!!
If you want to display the corresponding div then you can define the div with unique id. Then you can show corresponding div with the provided id of the element.
First set your div element with unique id as
<div id="myNavRef{{ref.pk}}" class="overlay">
Then on your button element onclick pass the same id as
<button onclick="openNavRef('{{ref.pk}}')" type="button" class="btn btn-outline-dark btn-sm">
Also for your close button as
Cancelar
Then in your javascript
<script>
function openNavRef(id) {
document.getElementById("myNavRef" + id).style.display = "block";
}
function closeNavRef(id) {
document.getElementById("myNavRef" + id).style.display = "none";
}
</script>
Related
I have created a Flask application that allows different users to register and log in. For this I have implemented sessions in my code. At the fist page new users arrive at, there is a modal welcoming them to the platform. I want to be able to show this modal only once to newly registered and logged in users. Alterations of this question have been answered in Stackoverflow but I tried them all and no answer helped me out.
So here is my code:
html page:
{% extends "layout.html" %}
{% block title %}
INDEX
{% endblock %}
{% block main %}
<div id="myModal" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Welcome!</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Welcome to the index page! Here you can trade to your heart's content with us by your side!<span class="badge">By Rahul jangid</span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<!--this closes, see what ull do -->
<button type="button" class="btn btn-primary">Move On</button>
<!--Here make sure to impplement the next fuinctionality. Look at changing the color of the popover. Also add some popovers.-->
</div>
</div>
</div>
</div>
<table class="table table-striped">
<thead>
<tr>
<th style ="color:red">Symbol</th>
<th style ="color:red">Name</th>
<th style ="color:red">Stock Shares</th>
<th style ="color:red">Price</th>
<th style ="color:red">Sum</th>
</tr>
<tbody>
{% for stock in stocks %}
<tr>
<td style ="color:red">{{stock.symbol}}</td>
<td style ="color:red">{{stock.name}}</td>
<td style ="color:red">{{stock.shares}}</td>
<td style ="color:red">{{stock.price | usd}}</td>
<td style ="color:red">{{stock.total | usd}}</td>
</tr>
{% endfor %}
<tr>
<td style ="color:red">CASH</td>
<td colspan ="3"></td>
<td style ="color:red"> {{cash | usd}}</td>
</tr>
</tbody>
</thead>
<tfoot>
<td style ="color:red">Initial Cash</td>
<td colspan ="3"></td>
<td style ="color:red">{{ total_cash | usd }} </td>
</tfoot>
</table>
{% endblock %}
javascript code:
$(document).ready(function () {
// Check if user saw the modal
var key = 'hadModal',
hadModal = localStorage.getItem(key);
// Show the modal only if new user
if (!hadModal) {
$('#myModal').modal('show');
}
// If modal is displayed, store that in localStorage
$('#myModal').on('shown.bs.modal', function () {
localStorage.setItem(key, true);
})
});
The problem with this code is that the modal showed only once and never again. (P.S. I have als tried the cookie approach, which didn't work either) It showed up just for one user and not for the other newly registered one. Any help would be greatly appreciated.
I think you need something like this
$(document).ready(function () {
var users = ['email1', 'email2'] //pushes all logged users here
function checkUsers() { //call this function on every log in
// Check if user saw the modal
var key = 'hadModal',
hadModal = JSON.parse(localStorage.getItem(key));
var loggedUserEmail //
// Show the modal only if new user
if (!hadModal) {
$('#myModal').modal('show');
users.push(loggedUserEmail) // push new user in users
} else {
if (!hadModal.includes(loggedUserEmail)) { // check if logged user is new
$('#myModal').modal('show');
users.push(loggedUserEmail) // push new user in users
}
}
// If modal is displayed, store that in localStorage
$('#myModal').on('shown.bs.modal', function () {
localStorage.setItem(key, JSON.stringify(users));
})
}
});
I have my for loop in Django such as its only opening the modal for the first element and nothing happens for other elements.
This is my HTML file it display all elements in a table with delete button. When clicking delete button a modal is opened but it is opened for the first element only, what should I change in this?
<table>
{% for card in cards %}
<tr class="record">
<td>{{card.number}}</td>
<td>
<button
class="hover:bg-gray-500 duration-500"
id="delete-btn"
>
</button>
<div
class="
fixed
flex
justify-center
items-center
hidden
"
aria-labelledby="modal-title"
aria-modal="true"
id="overlay"
>
............. #some lines of code
<div
class="
bg-gray-50
px-4
py-3
sm:px-6 sm:flex sm:flex-row-reverse
"
>
<a
href="{% url 'p:delete-card' card.id %}"
id="delbutton"
>
<button
type="button"
class="
w-full
inline-flex
justify-center
"
>
Delete
</button>
</a>
</div>
</div>
</div>
</td>
</tr>
{% endfor %}
My js to open the modal on button click
window.addEventListener('DOMContentLoaded',() =>{
const overlay = document.querySelector('#overlay')
const delbtn = document.querySelector('#delete-btn')
const toggleModal = () => {
overlay.classList.toggle('hidden')
overlay.classList.add('flex')
}
delbtn.addEventListener('click',toggleModal)
})
I solved it like this with the help of Data in Django for loop {% for %} not loading for Modal
I changed the id of all the buttons like this and added delete-button class!
<button class="hover:bg-gray-500 duration-500 delete-button" id="delete-btn_{{card.id}}">
</button>
Like this added card.id in overlay too.
My Jquery:
$(".delete-button").click(function() {
var id = $(this).attr("id").split("_")[1]
$(`#overlay_${id}`).show();
});
Every modal should have a different id in the for loop.
You can use something like id="modal{{card.id}}"
Then select that id
Does that help you?
i need to increment id field forms per form
default id which django provides is id_formsetname_set-0-fieldName and 0 increment one by one
in my case named id_items_set-0-model and for second form will be id_items_set-1-model it display in inspect element source code from browser , i used this for loo script
for (var i = 0; i < 10; i++){
$("#id_items_set-"+i+"-model").select2();
}
but only worked for the first form , i dont want to use django-select2
my template looks like this
this is my snippet
<tbody class="tbody tb1 " id="form_set">
{% for item in items.forms %}
<tr class="p-0 col-12">
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.price | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.quantity | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.model | add_class:'col-12 0model model' | attr:'id:id_items_set-0-model'}}
</div>
</td>
</tr>
{% endfor %}
</tbody>
<script type="text/javascript">
$(function(){
$('.tb1 tr:last').formset({
prefix:'{{items.prefix}}',
addText:'add',
deleteText:'remove',
addCssClass:'btn btn-success',
});
})
</script>
<script type="text/javascript">
$(document).ready(function(){
for (var i = 0; i < 10; i++){
$("#id_items_set-"+i+"-model").select2();
}
})
</script>
only work for my first form then doesnt have any effect on other forms ? is there something i did wrongly in the script part please?
jquery.formset has added attribute we can call a function every time when a row created
<script type="text/javascript">
$(function(){
$('.tb1 tr:last').formset({
prefix:'{{items.prefix}}',
addText:'add',
deleteText:'remove',
addCssClass:'btn btn-success',
added:function($row){
$('.model').select2()
}
});
})
</script>
I have never worked on django .
Could you try this please .
and if you could share with us a link for real example in case this doesn't work
$(()=>{
let ids = document.querySelectorAll("[id=*'id_items_set']");
ids.forEach((element)=>{
$(element).select2();
});
});
i want to use select2.min.js to auto-complete the choices (ForeignKey values) , but it only work for my first form , i used django formset for duplicate forms
this is my snippet
<tbody class="tbody tb1 " id="form_set">
{% for item in items.forms %}
<tr class="p-0 col-12">
<td class="">
<div class="col-12 p-0 mt-3 inp">
<input class="col-12 0qarz qarz" type="number" name="" placeholder="qarz">
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.price | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.quantity | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.model | add_class:'col-12 0model model' | attr:'id:model'}}
</div>
</td>
</tr>
{% endfor %}
</tbody>
<script type="text/javascript">
$(function(){
$('.tb1 tr:last').formset({
prefix:'{{items.prefix}}',
addText:'add',
deleteText:'remove',
addCssClass:'btn btn-success',
});
})
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#model").select2()
})
</script>
but the select2 only work for my first form then doesnt have any effect on other forms ! and how to set number of forms to add_class it will help to solve maybe?
thanks
First of all I would love to see a little bit more, for example how you actually define your formset. It is not also clear to me what are you trying to do here. Please paste more data.
I would suggest that you think about using django-select2 module that helps a lot with handling select2 stuff in django.
I am also not sure what you mean by "how to set number of forms", maybe you wish to include some incremental counter that can be done with {{ forloop }} inside for/endfor loop?
Please paste more stuff and answer will be better.
The selector you are using to initialize select2 #model is for element ids, which should be unique for each element in the DOM.
In most browsers the effect will be that only the first instance of an element id will be recognized, and the rest ignored as if they don't exist.
In this instance you want to use a class selector: .model. This will ensure select2 is initialized for all elements that have the class "model". So the code to initialize select2 would be:
<script type="text/javascript">
$(document).ready(function(){
$(".model").select2()
})
</script>
You have to reinitialize(like this way: $("#model").select2();) the select2 for other pages when they appear.
You should need separately initialize with different ids.
for example:
<script type="text/javascript">
$(document).ready(function(){
$("#id_1").select2();
$("#id_2").select2();
})
</script>
the way I found is sending the number of forms through context then apply for loop in the template.
views.py
get_context_data()
context.update({
"accessoryNum": len(StoreRequestAccessory.objects.filter(storeRequestId=self.object.pk)),
"oneDimensionalItemNum":len(StoreRequestOneDimensionalItem.objects.filter(storeRequestId=self.object.pk)),
"twoDimensionalItemNum":len(StoreRequestTwoDimensionalItem.objects.filter(storeRequestId=self.object.pk)),
})
template.html
{% block javascripts %}
<script>
{% comment %} get accessoryNum from context {% endcomment %}
var accessoryNum = {{accessoryNum}};
$(document).ready(function(){
for(let i = 0; i <=accessoryNum; i++){
$(`#id_storereq_accessory_form-${i}-accessoryId`).select2({
placeholder: "Select a Item",
allowClear: true
});
}
});
</script>
{% endblock javascripts %}
I have a table in HTML file:
{% for dimension in dimension_list %}
<tr>
<td>{{dimension.title}}</td>
<td>{{dimension.description}}</td>
<div class="button-group">
<td><button type="button" class="btn-click-del" data-
id="{{dimension.pk}}" id="btn-confirm" ></button></td>
</div>
</tr>
{% endfor %}
So I receive the value data-id (button) and pass it to a model:
$('.btn-click-del').on('click', function () {
var id = ($(this).data('id'));
$("#modal-btn-yes").val(id);
});
In the modal, I need to pass this id as parameter to the function dimension_remove in my yes button
div class="modal-dialog modal-bg modal-dialog-centered">
<button onclick="location.href='{% url 'dimension_remove' pk=dimension.id %}';" type="button" class="btn btn-default" id="modal-btn-yes">Yes</button>
<button type="button" class="btn btn-primary" id="modal-btn-no">No</button>
</div>
I suggest to attach the click event in your JS part instead and attach the id to the data-id to the modal-btn-yes then get it simply and build your URL.
Attach the data-id to the modal-btn-yes button :
$('.btn-click-del').on('click', function() {
$("#modal-btn-yes").data('id', $(this).data('id'));
});
Get the data-id and build the URL :
$('body').on('click', '#modal-btn-yes', function() {
//Here you could get the clicked button "id" like
var id = $(this).data('id');
//location.href= Your link here
});