Get data from thymeleaf to a modal bootstrap, jquery - javascript

I am trying to get an "id" to a modal view, this is in order to updated a "onclick" element, but I don't find a way :(, any idea how this could be done for boostrap 5 , ¿or other way I could do it? Thanks !
<tr th:each="user: ${users}">
<a data-bs-toggle="modal" th:title="active" th:id="${user.id}" th:attr="data-target='#modal-warning'+${user.id }" data-bs-target="#modal-view">inactivate</a>
<div th:fragment="modal" class="modal fade modal-warning" th:id="modal-warning+${clinicalRepresentative.id }" tabindex="-1" role="dialog" aria-labelledby="label-modal-1" >
<div class="modal-dialog">
<div class="modal-footer">
<input th:onclick="'location.href=\'/inactivate/' + (id=${clinicalRepresentative.id}) +'\''" />
<script>
$(document).ready(function() {
var id;
$('[title="active"]').click(function() {
id = $(this).attr('id');

Finally, thanks to lot of searching and trying, I found the solution, hope it helps with who is struggling, the trick is to put the modal inside the same loop of the table or div, and creating and dynamic "id" with the attribute sentence of thymeleaf, like is explained in this page for an older version:
<tr th:each="user: ${users}">
<td ><a data-bs-toggle="modal" data-row="${user}"
th:attr="data-bs-target='#modal-warning'+${user.id }">Inactivate</a>
<!-- MODAL -->
<div th:fragment="modal" class="modal fade" th:id="modal-warning+${user.id }" tabindex="-1"

Related

Update asp-route-id with jQuery

I'm building a razor pages application, and I want to use a modal as a partial view.
Foreach loop from where I'm opening the modal:
#foreach (var item in Model.SourceFiles)
{
<tr>
<td>#item.Id</td>
<td>#item.FileName</td>
<td>#item.Created</td>
<td>
#(item.IsConverted == true ? "Exported" : "Imported")
</td>
<td>
<button type="submit" class="btn btn-primary" asp-page-handler="FileContent" asp-route-fileId="#item.Id">View</button>
</td>
<td>
#if ((await authorizationService.AuthorizeAsync(User, "DeletePolicy")).Succeeded)
{
Delete
}
</td>
</tr>
}
I'm trying to set a new value of an asp-route-id tag using javaScript (jQuery), but I cant get it to work.
function triggerDeleteModal(itemId) {
$('#' + 'deleteModal').modal('toggle');
$("#confirmDeleteButton").attr('asp-route-deleteid', itemId)
}
Modal (partial view):
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalTitle">Caution!</h5>
</div>
<div class="modal-body">
<p style="white-space: pre-wrap;">#Model.DeleteModalText</p>
<p></p>
</div>
<div class="modal-footer">
<button type="submit" id="confirmDeleteButton" class="btn btn-secondary" data-bs-dismiss="modal">Yes</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
When pressing the yes-button (#confirmDeleteButton) in the modal to submit the form, the id is not getting passed in the asp-route-deleteid tag helper, and the id is always 0 in the OnPost-method.
Code behind where deleteid always is 0:
public async Task<IActionResult> OnPostAsync(int deleteid)
{
//code for deleting stuff
}
When trying to console.log the value of any attribute besides asp-route tags, the value is shown. When trying to log the value of an asp-route tag, the value is undefined.
Any ideas of how I can get the asp-route-deleteid to be passed to the code behind?
BR
The asp-route-* attribute works on tag helpers, which are server-side components. It is not rendered to the browser and is inaccessible to JavaScript. It is designed to work with elements that have an href, action or formaction attribute, and it either adds the attribute value to the query string of the generated href, or as a URL segment depending on the route template for the target page.
Generally, you shouldn't pass POST data within the URL, so instead, you can wire up a click event handler to the confirmDeleteButton that initiates an AJAX post that passes the deleteid:
$('#confirmDeleteButton').on('click, function(){
$.post('/yourpage',{deleteid: itemId}, function(){
// process the call back
})
})

Converting Bootstrap 3 remote modal to Bootstrap 4 modal with parameters

So in the near future my shop is going to upgrade to Bootstrap 4 but we cannot do this until we solve the issue with using remote modals. Here is an example of how we load our modals. The reason we use remote modals is because the modal-body is dynamic and may use different file based on the url. I have heard that using jQuery("#newsModal").on("load",..) is an alternative but how could I do this? I found this but I am not sure how my anchor would look and how to build the url to load the remote data.
Global PHP include file:
<div id="NewsModal" class="modal fade" tabindex="-1" role="dialog" data-
ajaxload="true" aria-labelledby="newsLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="newsLabel"></h3>
</div>
<div class="noscroll-modal-body">
<div class="loading">
<span class="caption">Loading...</span>
<img src="/images/loading.gif" alt="loading">
</div>
</div>
<div class="modal-footer caption">
<button class="btn btn-right default modal-close" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
modal_news.php file:
<form id="newsForm">
<div id="hth_err_msg" class="alert alert-danger display-hide col-lg-12 col-md-12 col-sm-12 col-xs-12">
You have some errors. Please check below.
</div>
<div id="hth_ok_msg" class="alert alert-success display-hide col-lg-12 col-md-12 col-sm-12 col-xs-12">
✔ Ready
</div>
<!-- details //-->
</form>
Here is how we trigger the modals :
<a href="#newsModal" id="modal_sbmt" data-toggle="modal" data-target="#newsModal"
onclick="remote='modal_news.php?USER=yardpenalty&PKEY=54&FUNCTION=*GENERAL'; remote_target='#NewsModal .noscroll-modal-body'">
<span class="label label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
Promotional Ordering
</a>
I think I need to do something like this when building anchor dynamically:
a) Replace paramters with data-attrs
b) Use the event invoker to get the data-attrs using event.target.id
Thanks to Tieson T. and this post I was able to effectively pass parameters to the remote modal using this technique except if you have multiple modals
I have also included some helpful techniques inside this example as to how you may pass parameters to the remote modal.
bootstrap_modal4.php:
<div class="portlet-body">
Add Attendee <i class="fa fa-plus"></i>
</div>
<!-- BEGIN Food Show Attendee Add/Edit/Delete Modal -->
<div id="attendee" class="modal fade" tabindex="-1" role="dialog" data-ajaxload="true" aria-labelledby="atnLabel" aria-hidden="true">
<form id="signupForm" method="post">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<label id="atnLabel" class="h3"></label><br>
<label id="evtLabel" class="h6"></label>
</div>
<div class="modal-body">
<div class="loading"><span class="caption">Loading...</span><img src="/images/loading.gif" alt="loading"></div>
</div>
<div class="modal-footer">
<span class="caption">
<button type="button" id="add_btn" class="btn btn-success add-attendee hidden">Add Attendee <i class="fa fa-plus"></i></button>
<button type="button" id="edit_btn" class="btn btn-info edit-attendee hidden">Update Attendee <i class="fa fa-save"></i></button>
<button type="button" id="del_btn" class="btn btn-danger edit-attendee hidden">Delete Attendee <i class="fa fa-minus"></i></button>
<button class="btn default modal-close" data-dismiss="modal" aria-hidden="true">Cancel</button>
</span>
</div>
</div>
</div>
</form>
</div>
<script>
jQuery(document).ready(function() {
EventHandlers();
});
function EventHandlers(){
$('#attendee').on('show.bs.modal', function (e) {
e.stopImmediatePropagation();
if($(this).attr('id') === "attendee"){
// Determines modal's data display based on its data-attr
var $invoker = $(e.relatedTarget);
var fscode = $invoker.attr('data-fscode');
console.log(fscode);
// Add Attendee
if($invoker.attr('data-atnid') === "add"){
$("#atnLabel").text("Add New Attendee");
$(".add-attendee").removeClass("hidden");
}
else{ //edit/delete attendee
$("#atnLabel").text("Attendee Maintenance");
$(".edit-attendee").removeClass("hidden");
}
//insert hidden inputs
//add input values for post
var hiddenInput = '<INPUT TYPE=HIDDEN NAME=FSCODE VALUE="' + fscode + '"/>';
$("#signupForm").append(hiddenInput);
}
});
$('#attendee').on('hidden.bs.modal', function (e) {
$(".edit-attendee").addClass("hidden");
$(".add-attendee").addClass("hidden");
$("#signupForm input[type='hidden']").remove();
});
// BOOTSTRAP 4 REMOTE MODAL ALTERNATIVE FOR BOOTSTRAP 3v-
$('#add-attendee').on('click', function(e){
$($(this).data("target")+' .modal-body').load($(this).data("remote"));
$("#attendee").modal('show');
});
}
</script>
bootstrap_remote_modal4.php:
<form id="signupForm">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
Hello World!
</div>
</form>
<script>
$(document).ready(function(){
console.log('<?php echo $_GET["USERNAME"]?>'); //passed through url
});
</script>
NOTE: I am having problems with event propagation during the show.bs.modal event which I have a global show.bs.modal that is propagating up to this event handler due to multiple modals so if you have multiple modals make sure to handle them correctly.
Here is a screen shot of the results which clearly show propagation is taking place but the parameter passing techniques are working.
You might find it easier to use something like Bootbox.js, which can be used to dynamically create Bootstrap modals.
Given what you've shown, it would work something like:
trigger modal
with
$(function(){
$('.show-modal').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.get(url)
.done(function(response, status, jqxhr) {
bootbox.dialog({
title: 'Your Title Here',
message: response
});
});
});
});
This assumes response is an HTML fragment.
Bootbox hasn't officially been confirmed to work with Bootstrap 4, but I haven't run into any problems with it yet (modals seem to be one of the few components that don't have updated markup in BS4).
Disclaimer: I am currently a contributor to Bootbox (mainly updating the documentation and triaging issues).
If you must use only the Bootstrap modal, you're actually after load(). You would probably do something like:
$(function(){
$('.show-modal').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
var dialog = $('#NewsModal').clone();
dialog.load(url, function(){
dialog.modal('show');
});
});
});

How to capture a button click event from a different page in a different View and make DOM manipulation in the source page?

I have the following html construct in the source Page View:
<i id="asterisk" class="fa fa-asterisk show asterisk" ></i>
<a id="tos" data-toggle="modal" data-target="#divTermsAndConditions" href="#Url.Action("TermsOfServiceFromRegistration", "Account", new { lk = ViewBag.LicenseKey })" target="_blank">
<div>
<div class="modal fade" id="divTAndC" role="dialog" data-backdrop="static" data-keyboard="false" aria-describedby="termsandconditions" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
#if (ViewData.ModelState.IsValid && fetchTOSAction) {
{ Html.RenderAction("TermsOfServiceFromRegistration", "Account", new { lk = ViewBag.LicenseKey }); }
}
</div>
</div>
</div>
</div>
And the new View which it opens, has a button:
<button class="btn btn-primary" id="btnClose" data-dismiss="modal">Close</button>
As you can see, it is a bootstrap button and on clicking of it, it closes the current window:"TermsofService.cshtml".
Now, my requirement is like this:
1.Capture this button click event
2.And on that event make some DOM manipulation in the source View, like :
$("#asterisk").removeClass("show").addClass("hide");
Is it possible?
Any help will be highly appretiated.
Thanks in advance.
Solved it myself!Bingo!
Here it is:
$("#divTAndC").on("hidden.bs.modal", function () {
$("#check").removeClass("hide").addClass("show");
});
Basically, in the source view itself,bind the function on modal close.
Thats it!

Bootstrap modal popup not working properly in aspx

i have this button B1 (say)
when i click on this B1 a modal popup appears with buttons / links
when i click the button / link a new popup should appear but i dont get the Modal window but i do get the values in firebug
Here is the code to the Button B1
<div class="thumbnail" ><img src="../Images/pix/B1.png" href="#B1Market" data-toggle="modal" /></div>
which then calls this modal popup which contains the content from the div divB1Market
<div class = "modal fade" id="B1Market" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Heading</h3>
</div>
<div class="modal-body">
<div id='divB1Market' runat="server"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Done</button>
</div>
</div>
</div>
The code below is the link / content inside the divB1Market
<a href='#' data-dismiss='modal' onclick='JavaScript:" + (user.RoleID == 3 ? "PlayerMP." : "") + "showFunctionDetails(1," + drMTDFunction["PlayerID"] + "," + SessionID + "," + SessionNum + ");'>Link here</a>
which inturn calls the ajax call
PlayerMP.getFunctionDetails = function (type, UserID, SessionID, SessionNo) {
$.ajax({
type: "GET",
url: PlayerMP.URL,
data: "rt=4&type=" + type + "&UserID=" + UserID + "&SessionID=" + SessionID + "&SessionNo=" + SessionNo,
success: function (FinancialSplitsJS) {
if (FunctionalSplitsJS.indexOf("SessionExpired=1", 0) == -1) {
$("#divFunctionalDetails").html(FunctionalSplitsJS);
switch (type) {
case 1:
$("#divFunctionalsSplit");
break;
}
$("#divFunctionalsSplit").show(); /* calling the div with this id in the aspx page */
}
else
window.location.href = "../Login.aspx?SessionExpired=1";
}
});}
This is the modal-popup content in the aspx page
<div class="modal fade" id="divFunctionalsSplit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <%--this is the one not showing up--%>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3>Content</h3>
</div>
<div class="modal-body">
<div id="divFunctionalDetails" style="color:Black;"></div>
</div>
</div>
</div>
</div>
This is what i get when i openup firebug and hover around with my cursor
But when i try to debug the code with firebug i get the responses (in the console) perfectly. I'm not able to figure out where the error might be.
This is the order of my importing the packages (posted this because i got this error while using )
$("#divFunctionalsSplit").modal().show();
Uncaught TypeError: Object #<Object> has no method 'modal'
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<!-- Start of BootStrap -->
<link href="../Scripts/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<script src="../Scripts/bootstrap.min.js" type="text/javascript"></script>
All I needed to add was jQuery.noConflict(); before $('#divID').modal('show')
it had to something to do with with other plugins conflicting.
This Helped Me
It would appear that the id of your modal is getting overwritten by ASP. It changes from #B1Market to #divFunctionalSplit. I assume your button still has an href of #B1Market. Simple solution would be to change the href to match the div id. Better solution would be to prevent ASP from replacing the id.

Reload content in modal (twitter bootstrap)

I'm using twitter bootstrap's modal popup.
<div id="myModal" class="modal hide fade in">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save"/>
</div>
</div>
I can load content using ajax with this a-element:
<a data-toggle="modal" data-target="#myModal" href="edit.aspx">Open modal</a>
Now I have to open the same modal but using a different url. I'm using this modal to edit an entity from my database. So when I click edit on an entity I need to load the modal with an ID.
<a data-toggle="modal" data-target="#myModal" href="edit.aspx?id=1">Open modal</a>
<a data-toggle="modal" data-target="#myModal" href="edit.aspx?id=2">Open modal</a>
<a data-toggle="modal" data-target="#myModal" href="edit.aspx?id=3">Open modal</a>
If I click on link number 1, it works fine. But if I then click on link number 2 the modal content is already loaded and therefor it will show the content from link number 1.
How can I refresh or reset the ajax loaded content in a twitter bootstrap modal popup?
I guess the way of doing this will be to remove the data-toggle attribute and have a custom handler for the links.
Something in the lines of:
$("a[data-target=#myModal]").click(function(ev) {
ev.preventDefault();
var target = $(this).attr("href");
// load the url and show modal on success
$("#myModal .modal-body").load(target, function() {
$("#myModal").modal("show");
});
});
To unload the data when the modal is closed you can use this with Bootstrap 2.x:
$('#myModal').on('hidden', function() {
$(this).removeData('modal');
});
And in Bootstrap 3 (https://github.com/twbs/bootstrap/pull/7935#issuecomment-18513516):
$(document.body).on('hidden.bs.modal', function () {
$('#myModal').removeData('bs.modal')
});
//Edit SL: more universal
$(document).on('hidden.bs.modal', function (e) {
$(e.target).removeData('bs.modal');
});
You can force Modal to refresh the popup by adding this line at the end of the hide method of the Modal plugin (If you are using bootstrap-transition.js v2.1.1, it should be at line 836)
this.$element.removeData()
Or with an event listener
$('#modal').on('hidden', function() {
$(this).data('modal').$element.removeData();
})
With Bootstrap 3 you can use 'hidden.bs.modal' event handler to delete any modal-related data, forcing the popup to reload next time:
$('#modal').on('hidden.bs.modal', function() {
$(this).removeData('bs.modal');
});
Based on other answers (thanks everyone).
I needed to adjust the code to work, as simply calling .html wiped the whole content out and the modal would not load with any content after i did it. So i simply looked for the content area of the modal and applied the resetting of the HTML there.
$(document).on('hidden.bs.modal', function (e) {
var target = $(e.target);
target.removeData('bs.modal')
.find(".modal-content").html('');
});
Still may go with the accepted answer as i am getting some ugly jump just before the modal loads as the control is with Bootstrap.
A little more compressed than the above accepted example. Grabs the target from the data-target of the current clicked anything with data-toggle=modal on. This makes it so you don't have to know what the id of the target modal is, just reuse the same one! less code = win! You could also modify this to load title, labels and buttons for your modal should you want to.
$("[data-toggle=modal]").click(function(ev) {
ev.preventDefault();
// load the url and show modal on success
$( $(this).attr('data-target') + " .modal-body").load($(this).attr("href"), function() {
$($(this).attr('data-target')).modal("show");
});
});
Example Links:
<a data-toggle="modal" href="/page/api?package=herp" data-target="#modal">click me</a>
<a data-toggle="modal" href="/page/api?package=derp" data-target="#modal">click me2</a>
<a data-toggle="modal" href="/page/api?package=merp" data-target="#modal">click me3</a>
I made a small change to Softlion answer, so all my modals won't refresh on hide.
The modals with data-refresh='true' attribute are only refreshed, others work as usual.
Here is the modified version.
$(document).on('hidden.bs.modal', function (e) {
if ($(e.target).attr('data-refresh') == 'true') {
// Remove modal data
$(e.target).removeData('bs.modal');
// Empty the HTML of modal
$(e.target).html('');
}
});
Now use the attribute as shown below,
<div class="modal fade" data-refresh="true" id="#modal" tabindex="-1" role="dialog" aria-labelledby="#modal-label" aria-hidden="true"></div>
This will make sure only the modals with data-refresh='true' are refreshed. And i'm also resetting the modal html because the old values are shown until new ones get loaded, making html empty fixes that one.
Here is a coffeescript version that worked for me.
$(document).on 'hidden.bs.modal', (e) ->
target = $(e.target)
target.removeData('bs.modal').find(".modal-content").html('')
It will works for all version of twitterbootstrap
Javascript code :
<script type="text/javascript">
/* <![CDATA[ */
(function(){
var bsModal = null;
$("[data-toggle=modal]").click(function(e) {
e.preventDefault();
var trgId = $(this).attr('data-target');
if ( bsModal == null )
bsModal = $(trgId).modal;
$.fn.bsModal = bsModal;
$(trgId + " .modal-body").load($(this).attr("href"));
$(trgId).bsModal('show');
});
})();
/* <![CDATA[ */
</script>
links to modal are
<a data-toggle="modal" data-target="#myModal" href="edit1.aspx">Open modal 1</a>
<a data-toggle="modal" data-target="#myModal" href="edit2.aspx">Open modal 2</a>
<a data-toggle="modal" data-target="#myModal" href="edit3.aspx">Open modal 3</a>
pop up modal
<div id="myModal" class="modal hide fade in">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save"/>
</div>
I was also stuck on this problem then I saw that the ids of the modal are the same. You need different ids of modals if you want multiple modals. I used dynamic id. Here is my code in haml:
.modal.hide.fade{"id"=> discount.id,"aria-hidden" => "true", "aria-labelledby" => "myModalLabel", :role => "dialog", :tabindex => "-1"}
you can do this
<div id="<%= some.id %>" class="modal hide fade in">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save" />
</div>
</div>
and your links to modal will be
<a data-toggle="modal" data-target="#" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>
I hope this will work for you.
You can try this:
$('#modal').on('hidden.bs.modal', function() {
$(this).removeData('bs.modal');
});
I wanted the AJAX loaded content removed when the modal closed, so I adjusted the line suggested by others (coffeescript syntax):
$('#my-modal').on 'hidden.bs.modal', (event) ->
$(this).removeData('bs.modal').children().remove()
var $table = $('#myTable2');
$table.bootstrapTable('destroy');
Worked for me
step 1 : Create a wrapper for the modal called clone-modal-wrapper.
step 2 : Create a blank div called modal-wrapper.
Step 3 : Copy the modal element from clone-modal-wrapper to modal-wrapper.
step 4 : Toggle the modal of modal-wrapper.
<a data-toggle="modal" class='my-modal'>Open modal</a>
<div class="clone-modal-wrapper">
<div class='my-modal' class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save"/>
</div>
</div>
</div>
</div>
</div>
<div class="modal-wrapper"></div>
$("a[data-target=#myModal]").click(function (e) {
e.preventDefault();
$(".modal-wrapper").html($(".clone-modal-wrapper").html());
$('.modal-wrapper').find('.my-modal').modal('toggle');
});

Categories

Resources