Include template with dynamic Django form - javascript

I have a model with a choices field, and the creation form has different fields depending on the field. I'm implementing the design of a dashboard in which the user can click a button (one button for each choice) and a model containing the model form will be displayed.
I want to use a template only for the model and send the form and action URL to it depending on which button the user clicks, but that would mean I have to mix JS and Django variables and I don't know if that's a good idea.
The code right now is something like this:
dashboard.html
<div class="add-connections">
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.EP %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.OLX %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.CC %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if user_connections.FR %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
</div>
{% url 'create_olx_connection' as olx_url %}
{% url 'create_ep_connection' as ep_url %}
{% url 'create_cc_connection' as cc_url %}
{% url 'create_fr_connection' as fr_url %}
{% include "properties/dashboard/connection_modal.html" %}
connection_modal.html
<!-- Modal -->
<div class="modal fade modal-property" id="modal-new-connection" tabindex="-1" role="dialog" aria-labelledby="myConnectionModal">
<div class="modal-dialog" role="document">
<div class="modal-content panel-success">
<div class="modal-header panel-heading">
<button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title text-uppercase text-white"><b>Connections</b></h4>
</div>
<div class="modal-body">
<form action="{{ action_url }}"
{{ form.as_p }}
<div>
<button type="submit" class="btn btn-outline-success">Activate connection</button>
Cancel
</div>
</form>
</div>
</div>
</div>
</div>
views.py
def get_context_data(self, **kwargs):
context = super(
ManageServicesView, self).get_context_data(**kwargs)
...
context['connection_forms'] = {
'olx_form': OLXform(),
'el_pais_form': ElPaisForm(),
'finca_raiz_form': FincaRaizForm(),
'calicasa_form': CaliCasaForm()
}
return context
I want something like {% include "properties/dashboard/connection_modal.html" with form=chosen_form and action_url=chosen_url %} but I don't know how to link each button's click event with Django variables to be able to do that. I don't want to code a model for each option, I think it has to be a cleaner way. I'd appreciate your suggestions.

You could put a {% for ... %} loop in connection_modal.html to generate all the modals, with the correct forms, that you need. Than put a another for loop in dashboard.html to create the correct links.
Tweaking views.py:
context['connections'] = {
'OLX': {
'form' : OLXform(),
'user_connected': user_connections.OLX
},
'EP': {
'form' : ElPaisForm(),
'user_connected': user_connections.EP
},
# other connections here
}
dashboard.html:
{% for connection,data in user_connected.items %}
<div class="col-sm-3 text-center" >
<div class="connection-box">
{% if data.user_connected %}
<img src="{% static 'images/green-check-mark.png' %}" alt="Connection added" class="check">
{% else %}
Activate
{% endif %}
</div>
</div>
{% endfor %}
connection_modal.html:
{% for connection,data in user_connected.items %}
{% if not data.connected %}
<!-- Modal for {{connection}} -->
<div id="modal-new-connection-{{connection}}" class="modal fade modal-property" tabindex="-1" role="dialog" aria-labelledby="myConnectionModal">
<!-- modal code before form -->
{{ data.form }}
<!-- modal code after form -->
</div>
{% endif %}
{% endfor %}
This should create as many modals as you need, each with their own id value, that can be called from the appropriate link. For example modal id "modal-new-connection-OLX" will be created with the OLX form and be called from the OLX link.

Related

How to use Flask-Moment with dynamically generated HTML?

I have API that generates table that uses Flask-Moment. API returns HTML code and then it's displayed on the page, but column that uses Flask-Moment is empty. I think it's somehow connected with the fact that Flask-Moment can't (probably) work with dynamically generated HTML.
So, how to use Flask-Moment with dynamically generated HTML?
Table screenshot
responses/submissions.html:
<div class="submissions_table">
<div class="table_header__wrapper">
<div class="table_header">
{# Result #}
<div class="table_header_column result">
<p>RESULT</p>
</div>
{# Language #}
<div class="table_header_column language">
<p>LANGUAGE</p>
</div>
{# Time #}
<div class="table_header_column time">
<p>TIME</p>
</div>
{# View result #}
<div class="table_header_column view_result"></div>
</div>
</div>
<div class="table_body">
{% for submission in submissions %}
<div class="table_row__wrapper">
<div class="table_row">
{# Result #}
{% set submission_result = submission.get_result() %}
{% if submission_result['success'] %}
{% set result_status = 'success' %}
{% else %}
{% set result_status = 'fail' %}
{% endif %}
<div class="table_row_column result {{ result_status }}">
{# Status icon #}
{% if submission_result['success'] %}
<i class="result__icon far fa-check-circle"></i>
{% else %}
<i class="result__icon far fa-times-circle"></i>
{% endif %}
<p>{{ submission_result['message'] }}</p>
</div>
{# Language #}
<div class="table_row_column language">
{% set language_info = languages.get_info(submission.language) %}
<img src="{{ language_info['icon'] }}" alt="" class="language__icon">
<p class="language__name">{{ language_info['fullname'] }}</p>
</div>
{# Time #}
<div class="table_row_column time">{{ moment(submission.submission_date).fromNow() }}</div>
{# View result #}
<div class="table_row_column view_result">View Result</div>
</div>
</div>
{% endfor %}
</div>
</div>

Django - Why does this TableView has two paginators?

In my Django project I have a view that has two paginators, and I can't identify where each of them comes from. They look like this:
I want to delete one of them, but I realized they are not working the same way.
The one above to the right always paginates 25 results (10 on the first, 10 on the second and 5 on the third page.
The one below seems to be dividing the whole queryset in sets of 25, which then the other paginator iterates over.
So, for example, if I have 100 rows, the paginator below says there's 4 pages. If I select the number 2 in that paginator, the paginator on the right iterates over those 25 rows, and not the whole queryset.
My view looks like this:
class ClientTableView(AdminPermissionsMixin, PagedFilteredTableView):
model = Client
table_class = ClientTable
template_name = 'users/client/client_table.html'
filter_class = ClientFilter
formhelper_class = ClientFormHelper
exclude_columns = ('actions',)
export_name = 'regiones'
def get_context_data(self, **kwargs):
context = super(ClientTableView, self).get_context_data(**kwargs)
context['allows_user_creation'] = self.request.user.users_permission == '2'
return context
def get_queryset(self, **kwargs):
qs = super(ClientTableView, self).get_queryset()
qs = qs.filter(allows_credit=False)
return qs
The template client_table.html looks like this:
{% extends "table.html" %}
{% load staticfiles %}
{% block users_active %}active{% endblock %}
{% block page_title %}Clientes{% endblock page_title %}
{% block table_title %}Lista de clientes{% endblock %}
{% block breadcrumb %}
{{ block.super }}
<li class="breadcrumb-item accordion active">Lista de clientes</li>
{% endblock %}
{% block table_actions %}
<a href="{% url "credit_client_list" %}" class="mb-sm btn btn-primary" style="margin-right: 10px">Clientes
cartera</a>
{% if allows_user_creation %}
<i class="fa fa-plus-square"></i>Agregar cliente
{% endif %}
{{ block.super }}
{% endblock %}
{% block js %}
<script src="{% static "js/table-spanish.js" %}"></script>
{% endblock %}
And table.html looks like this:
{% extends "base.html" %}
{% load django_tables2 crispy_forms_tags staticfiles %}
{% block content %}
<div class="card card-custom gutter-b">
<div class="card-header flex-wrap py-3">
<div class="card-title">
<h3 class="card-label">
<i class="fas {% block table_icon %}fa-list-alt{% endblock %}"></i>
{% block table_title %}{% endblock %}
</h3>
</div>
<div class="card-toolbar">
{% block table_actions %}
{% if object_list|length > 0 %}
<div class="dropdown dropdown-inline ml-2">
<button type="button" class="btn btn-light-primary font-weight-bolder dropdown-toggle"
data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="fas fa-file-export"></i>Exportar
</button>
<!--begin::Dropdown Menu-->
<div class="dropdown-menu dropdown-menu-sm dropdown-menu-right" style="">
<!--begin::Navigation-->
<ul class="navi flex-column navi-hover py-2">
<li class="navi-header font-weight-bolder text-uppercase font-size-sm text-primary pb-2">
Elige una opción:
</li>
<li class="navi-item">
<a href="{% url 'export_pdf' "local" %}" class="navi-link">
<span class="navi-icon">
<i class="far fa-file-pdf"></i>
</span>
<span class="navi-text">PDF</span>
</a>
</li>
<li class="navi-item">
<a href="{% url 'export_xlsx' "local" %}" class="navi-link">
<span class="navi-icon">
<i class="far fa-file-excel"></i>
</span>
<span class="navi-text">XLSX</span>
</a>
</li>
</ul>
<!--end::Navigation-->
</div>
<!--end::Dropdown Menu-->
</div>
{% endif %}
{% endblock %}
</div>
</div>
<div style="display: inline-block">
{% block table_statistics %}{% endblock %}
</div>
<div class="card-body">
{% block body_table %}
<div class="row">
<div class="col-sm-12 col-md-12 mb-5">
<div id="datatable1_filter" class="dataTables_length">
{% crispy filter.form %}
{# <label>Buscar:<input type="search" class="form-control form-control-sm" placeholder="" aria-controls="DataTables_Table_0"></label>#}
</div>
</div>
</div>
<form action="{% block url_table_actions %}{% endblock %}" method="post" id="action">
{% csrf_token %}
{% block table %}
{% render_table table "django_tables2/bootstrap4.html" %}
{% endblock %}
<input type="hidden" name="command" id="command"/>
</form>
{% endblock %}
{% block table_bottom %}
{% endblock table_bottom %}
</div>
</div>
{% endblock %}
{% block js %}
{# <script src="{% static "js/datatables.bundle.js" %}"></script>#}
<script src="{% static "js/basic.js" %}"></script>
{% endblock %}
WHAT I KNOW
I identified that the paginator on the right, is added by the line <script src="{% static "js/table-spanish.js" %}"></script> in client_table.html, and if I remove that line, that paginator disappears, and the other one iterates correctly over the whole queryset.
However, I would really like to keep that line, since it also gives me other functionalities which I'd rather keep simple.
I'd like to identify what line or library could be responsible for the other paginator, the one below and, if possible, delete that one instead and let the paginator on the right iterate over the whole queryset.
I think you're right side pagination is datatables.js and the lower pagination is from Django-tables2. Django-tables2 is going to give you pagination for that by default, you can easily disable it.
https://django-tables2.readthedocs.io/en/latest/pages/pagination.html#disabling-pagination
Just add table_pagination = False
class ClientTableView(AdminPermissionsMixin, PagedFilteredTableView):
table_pagination = False
(django-filters' PagedFilteredTableView inherits from django-tables2' SingleTableView)

django template tag in static js files

I want to use template tag and variables in static js files.
I'll give you 3 files.
no1_ index.html
no2_ inc/index.html
no3_ index javascript file
no1 file is template. html tags in here.
and it refers to no2.file to include some scripts.
no2.file has some kinds of script includes.
and it refers to no3.file to make my own scripts.
in no3.file, I want to deal with my template variables from view.py
but at no3.file, It can not read template tags and variables.
what can I do for this issue?
no1_index.html
{% load static %}
{% load mathfilters %}
{% extends 'mobileWeb/base/base.html' %}
{% block content %}
{% include 'mobileWeb/inc/index/index.html' %}
<div id="map" style="width:80%;height:300px; margin:20px auto; border-radius: 10px;"></div>
<div style="width:90%; margin:auto">
<!-- this row will wrapping foreach-->
{% for mart in marts %}
<div class="row">
<div class="col-xs-5" onclick="martClick({{ mart }})">
{% with "/mobileWeb/images/"|add:mart.imageFileNo|add:".png" as path %}
<img src="{% static path %}" style="width:120px; height:120px; margin-top:10px;">
<br>
<h3>{{ mart.name }}</h3>
{% endwith %}
</div>
<div class="col-xs-7" style="height:200px; overflow:scroll" data-toggle="modal" data-target="#martModal"
data-whatever="{{ mart.id }}_{{ mart.name }}">
{% for item in items %}
{% if mart.id == item.mart %}
<div>
<h4 style="color:mediumpurple;">{{ item.name }}</h4>
{% if item.discountPrice == 1 or item.discountPrice == 100 %}
<h6><span
style="color:red">{{ item.originalPrice|sub:item.discountPrice|div:item.originalPrice|mul:100|floatformat:"0" }}% 할인</span>
</h6>
{% else %}
<h6>할인판매가 : {{ item.discountPrice }}원 <span
style="color:red">{{ item.originalPrice|sub:item.discountPrice|div:item.originalPrice|mul:100|floatformat:"0" }}% 할인</span>
</h6>
{% endif %}
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endfor %}
<!-- Mart Modal -->
<div class="modal fade" id="martModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" id="modal-title"></h4>
</div>
<div class="modal-body" id="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Item Modal -->
<div class="modal fade" id="itemModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="itemModal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="itemModal-title" id="itemModal-title" onclick="purchaseItem()"></h4>
</div>
<div class="itemModal-body" id="itemModal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onClick="stopTimer()">취소
</button>
</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
no2 inc/index.html
{% load static %}
<!-- outter module-->
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-159115722-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', 'UA-159115722-1');
</script>
<!-- kakao map -->
<script type="text/javascript"
src="//dapi.kakao.com/v2/maps/sdk.js?appkey=2a40b9e58744cbe7d0cb367e51c07eb4"></script>
<!-- css -->
<link rel="stylesheet" href="{% static 'mobileWeb/css/index/index.css' %}">
<!--js-->
{% block javascript %}
<script src="{% static 'mobileWeb/js/index/index.js' %}"></script>
{% endblock %}
no3 index javascript file
function writeMartModal(martId, martName) {
console.log("martID : " + martId);
document.getElementById('modal-body').innerHTML = '';
document.getElementById('modal-title').innerHTML = martName;
{% for item in items %}
var itemMartId = {{ item.mart }};
if (martId == itemMartId) {
var itemId = {{ item.id }};
var itemName = '{{ item.name }}';
var itemPrice = {{ item.discountPrice }};
var itemExpirationDate = '{{ item.expirationDate|date:"m월d일 H시 i분 까지" }}';
{% autoescape off %}
var itemComment = '{{ item.comment }}';
{% endautoescape %}
var html = "";
var div = document.createElement('div');
html += `
<div>
<div data-toggle="modal" data-target="#itemModal" data-whatever="${martName}_${itemId}_${itemName}">
<h4 style = "color:mediumpurple;" > ${itemName} </h4>
<h6> ${itemPrice}원 </h6>
<h6> ${itemExpirationDate} </h6>
</div>
{% autoescape off %}
<h6 style="color:red">${itemComment}</h6>
{% endautoescape %}
</div>
`
div.innerHTML = html;
document.getElementById('modal-body').appendChild(div);
}
{% endfor %}
};
errors in javascript file

jQuery's fadeToggle() selects more elements than desired

$(document).ready(function(event) {
$(".reply-btn").click(function() {
$(".section-row-reply").closest(".section-row-reply").fadeToggle();
});
});
I have a for-loop that generates the following:
comments
replies
reply form.
I want the jquery function,fadeToggle() to reveal the reply form for each comment when the reply button is clicked
<!-- jquery 2.2.4 -->
<script src="{% static 'js/jquery.min.js' %}"></script>
<!-- bootstrap 3.3.7 -->
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script src="{% static 'js/jquery.stellar.min.js' %}"></script>
<script src="{% static 'js/main.js' %}"></script>
<!-- post comments -->
<div class="section-row">
<div class="section-title">
<h3 class="title">{{ comments.count }} Comment{{ comments|pluralize }}</h3>
</div>
<div class="post-comments">
{% for comment in comments %}
{% if comment %}
<!-- comment -->
<div class="media">
<div class="media-left">
<img class="media-object" src="{{ comment.profile_picture.url }}" alt="">
</div>
<div class="media-body">
<div class="media-heading">
<h4>{{ comment.user }}</h4>
<span class="time">{{ comment.timestamp }}</span>
</div>
<p>{{ comment.content }}</p>
<div class="rely-button">
<button type="button" name="button" class="reply-btn btn btn-outline-dark btn-sm" id="reply-button">Reply</button>
</div>
<br>
<!-- display replies to the comment -->
{# reply per comment #}
{# all replies to comments will be shown below the comment #}
{% if comment.replies %}
{% for reply in comment.replies.all %}
<div class="media-replies pull-right">
<div class="media-left">
<img class="media-object" src="{{ reply.profile_picture.url }}" alt="">
</div>
<div class="media-body">
<div class="media-heading">
<h4>{{ reply.user }}</h4>
<span class="time">{{ reply.timestamp }}</span>
</div>
<p>{{ reply.content }}</p>
</div>
</div>
{% endfor %} {# endfor comment.replies #}
{% endif %} {# endif comment.replies #}
<!-- /display replies to parent comment -->
{# after replies have been shown, we can have the reply-comment-form #}
{% if user.is_authenticated %}
<!-- post reply -->
<div class="section-row-reply pull-right" style="display:none" id="show-reply-form">
<form class="post-reply" method="post">
{% csrf_token %}
<input type="hidden" name="comment_id" value="{{ comment.id }}">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<textarea class="input" name="content" placeholder="Reply here..."></textarea>
</div>
</div>
<div class="col-md-12">
<button class="primary-button" value="submit" type="submit">Reply</button>
</div>
<!-- form_errors -->
{{ comment_form.errors }}
</div>
</form>
</div>
<!-- /post reply -->
{% endif %} {# endif user.is_authenticated #}
{# comments are display in the manner above in the div section #}
</div>
</div>
{% endif %} {# endif comment #}
{% endfor %} {# endfor comment in comments #}
</div>
</div>
<!-- /post comments -->
This is a django powered site hence the {% %}, {# #} and {{ }} at the html layer. The function works but not exactly. When any reply button is clicked (to display the reply form), other reply forms for other comments are displayed.
**The idea is to make the reply button for each comment display only the reply form for that comment. Any help will be greatly appreciated. I suspect my selection of elements at the jquery layer. **
all css are that of bootstrap 3.3.7

Removing bootstrap Modal from DOM

I am working on a piece of code to load part of my content dynamically after user triggers the event by clicking.
Case Scenario is: when user clicks on the post, it will open a modal and display the detailed view which is the dynamic generated content using the slug in the link. However, I need to remove the modal from the DOM when user closes the modal. for now i have only been able to hide it but I need to remove it.
here is my code.
PHP Laravel HTML Markup ():
<div class="content-blocks blog hidex">
<section class="content">
<div class="block-content">
<h3 class="block-title">My Blog</h3>
<div id="post-list" class="col-md-10 col-md-offset-1">
{% set posts = blogPosts.posts %}
{% for post in posts %}
<div class="post">
<div class="post-thumbnail">
{% if post.featured_images.count %}
{% set image = post.featured_images|first %}
<a class="open-post" href="{{'blog-post'|page}}">
<img
data-src="{{ image.filename }}"
src="{{ image.path }}"
alt="{{ image.description }}"
style="max-width: 100%"/>
</a>
{% endif %}
</div>
<div class="post-title">
<a class="open-post" href="{{ post.url }}"><h2>{{ post.title }}</h2></a>
<p class="post-info">
<span class="post-author">Posted by {{ post.user.first_name}} </span>
<span class="slash"></span>
<span class="post-date">on {{ post.published_at|date('M d, Y') }}</span>
<span class="slash"></span>
{% if post.categories.count %} in {% endif %}
{% for category in post.categories %}
<span class="post-category">{{ category.name }}</span>
{% if not loop.last %}, {% endif %}
{% endfor %}
</p>
</div>
<div class="post-body">
<p>{{ post.summary }}</p>
<a class="btn open-post" href="{{ post.url }}">Read More</a>
</div>
</div>
{% endfor %}
<div class="text-center">
{% if posts.lastPage > 1 %}
<ul class="pagination">
{% if posts.currentPage > 1 %}
<li>
<a href="{{ this.page.baseFileName|page({ (pageParam): (posts.currentPage-1) }) }}"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a></li>
{% endif %}
{% for page in 1..posts.lastPage %}
<li class="{{ posts.currentPage == page ? 'active' : null }}">
{{ page }}
</li>
{% endfor %}
{% if posts.lastPage > posts.currentPage %}
<li><a href="{{ this.page.baseFileName|page({ (pageParam): (posts.currentPage+1) }) }}"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
{% endif %}
</ul>
{% endif %}
</div>
</div>
</div>
</section>
</div>
JavaScript:
//Blog post Modal
$('.open-post').on('click', function(){
var postUrl = $(this).attr("href");
var post = '<div class="modal" id="post-modal"><div class="inline-menu-container"><a id="modal-close" class="close" data-dismiss="modal"><span aria-hidden="true">×</span></a></div><div class="modal-dialog"><div class="modal-content"></div></div></div>';
$(post).modal({
remote: postUrl
})
return false;
});
// close the modal
$('#close').on( 'click', function() {
$('.name-block').removeClass('reverse');
$('.name-block-container').removeClass('reverse');
$('.menu-blocks').removeClass('hidex');
$('.content-blocks').removeClass('showx');
$('.content-blocks').addClass('hidex');
$('.inline-menu-container').removeClass('showx');
$('.inline-menu-container').addClass('hidex');
$('.menu-item').removeClass('active');
});
result of Javascript code in the DOM:
<div class="modal in" id="post-modal" style="display: block; padding-left: 0px;">
<div class="inline-menu-container">
<a id="modal-close" class="close" data-dismiss="modal"><span aria-hidden="true">×</span></a>
</div>
<div class="modal-dialog">
<div class="modal-content">
/// all the dynamic content in the modal
</div>
</div>
Now I need to remove this result without refreshing the page.
Update:
This is how it looks in the HTML in Inspect after closing the modal:
Note:
I tried to remove the modal content from the DOM using the #post-modal id but wasn't successful. also, i haven't been able to find an example of using Delegate while the modal elements and content are completely added by javascript after loading the 'DOM'.
Bind an event and then remove().
$('.modal').on('hidden.bs.modal', function () {
$(this).remove();
});
or
$('.modal').on('hidden.bs.modal', function () {
$('.modal').remove();
});
Thanks to I.G. Pascual and Serg Chernata here is the solution:
Javascript code:
$(document).on('hidden.bs.modal', '.modal', function () { $("#post-modal").remove(); $(".modal-dialog").remove(); });
you can try this
$(modal).modal().on('hidden.bs.modal',function(e){
e.target.remove();
})
you can directly add the hidden event on the initialization itself. so you don't have to trigger separately each time.
Below given snippet will show you how can you do something that you want without having to do anything extra and also by not even writing conventional bootstrap modal code.
For further reference you can also visit this link. It will show you how you can create modal dynamically with minimum efforts.
function open_modal(name) {
var message = $('#frm_1');
BootstrapDialog.show({
title: 'New message to ' + name,
message: $('#frm_1'),
onshown: function() {
$('#recipient-name').val(name);
},
onhide: function(dialog) {
console.log('Cerrada');
$('#hidden-div').append(message);
},
buttons: [{
label: 'Close',
action: function(dialog) {
dialog.close();
}
}, {
label: 'Send message',
cssClass: 'btn btn-primary',
action: function(dialog) {
// Do whatever send message does, here
}
}]
});
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/css/bootstrap-dialog.min.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.34.7/js/bootstrap-dialog.min.js"></script>
<button type="button" class="btn btn-primary" onclick="open_modal('#mdo')">Open modal for #mdo</button>
<button type="button" class="btn btn-primary" onclick="open_modal('#fat')">Open modal for #fat</button>
<button type="button" class="btn btn-primary" onclick="open_modal('#getbootstrap')">Open modal for #getbootstrap</button>
<div id="hidden-div" style="display : none">
<form id="frm_1">
<div class="form-group">
<label for="recipient-name" class="control-label">Recipient:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label for="message-text" class="control-label">Message:</label>
<textarea class="form-control" id="message-text"></textarea>
</div>
</form>
</div>

Categories

Resources