on button click add action url jquery - javascript

I have a link like this:
<a class="glyphicon glyphicon-remove glyphicon-color-red btn-delete" data-toggle="modal" data-target="#myModal" user-id="56f52ea551d72027711157d6"></a>
And with jquery, on click I take parameter user-id and I change action URL, this code isn't working cause when I click the delete button modal popup appears, but if I do inspect element I see that action is empty?
$('.btn-delete').click(function () {
var user_id = $(this).attr('user-id');
$('#modal-form').attr('action', "{{ url_for('admin.delete_user', id=" +user_id+" ) }}");
});
The method that I use in route admin.delete_user in python is:
def delete_user(self, id):
mongo.db.users.remove({'_id': ObjectId(id)})
return redirect(url_for('admin.users'))
And the modal popup:
<div class="modal fade" id="myModal" 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"><span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span></h4>
</div>
<form id="modal-form" action=" " method="POST">
<div class="modal-body">
<p>Are you sure?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-sm btn-style" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default btn-sm btn-filter-apply btn-style" >Yes</button>
</div>
</form>
</div>
</div>
I don't understand why in jquery the action URL is not added?

Make sure that the DOM has loaded before you make any changes, for which you can use ready():
$(document).ready(function(){ /* your code */ });

I would change your url_for function to to produce part of the url you need, then place it in the action attr. Then, use jquery to append the user_id to the string. Make sure you modify whatever is grabbing the url to parse a parameter. Here's an example:
url_for returns something like: http://www.example.com?delete_user=
Then your form action:
<form id="modal-form" action="{{url_for(delete_user)}}" method="POST">
And your jquery would then:
$('.btn-delete').click(function () {
var user_id = $(this).attr('user-id');
var action = $('#modal-form').attr('action');
$('#modal-form').attr('action', action + user_id);
});
Finally, whatever is parsing your form would look for the url parameter delete_user= and use the user_id you appended to it.

Related

Modal won't close and prevent default on no click, and won't execute func on yes click

I have a modal with two buttons. One is a yes button and one is a no button. If yes button is pressed, I would like the remainder of the function to execute. If no btn clicked, I would like the page to prevent default and not execute. However, it seems that regardless of which button is clicked, nothing happens besides the modal closing. I am using a modal example I found elsewhere, so this may be the issue. After glancing at it for some time I cannot seem to find where the issue is. Am I missing something small? Or perhaps my Jquery is wrong? Below is my code:
Modal:
<!-- Modal for delete-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content border-primary mb-3 box-shadow-none img-responsive">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="card-body bg-light">
<div id="del" class="center">
<label>Are you sure you want to delete?</label>
</div>
</div>
<div class="modal-footer">
<div id="deleteYes">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteYes">Yes</button>
</div>
<div id="deleteNo">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteNo">No</button>
</div>
</div>
</div>
</div>
</div>
And here is my Jquery:
$(".btnDeleteTerminalCommand").click(function (e) {
$("#deleteModal").modal('toggle');
if ($("#deleteNo").click) {
return e.preventDefault();
}
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
var termId = row.find(".tdTermId").html().trim();
var cmdId = row.find(".tdCmdId").html().trim();
var cmdVal = row.find(".tdCmdVal").html().trim();
var cmdID = row.find(".cmdID").html().trim();
var data = {
TerminalID: termId,
CommandID: cmdId,
CommandValue: cmdVal,
ID: cmdID
};
$.ajax({
url: '#Url.Action("DeleteTerminalCommand", "TerminalCommand")',
type: "POST",
data: data,
success: function (response) {
console.log("Success");
window.location.href = response.Url;
}
});
});
Any advice helps! Thank you!
Your click handler will toggle the modal and immediately continue to execute the rest of the function before the user can click anything. If your modal has two buttons, create a click handler for each button. Perhaps the No button just closes the modal. The Yes button handler can execute the actions required to accomplish the task.
$(".btnDeleteTerminalCommand").click(function(e){
$("#deleteModal").modal('toggle');
}
$("#deleteNo").click(function(e){
$("#deleteModal").modal('hide');
}
$("#deleteYes").click(function(e){
// build data object
// ajax post
}

Bootstrap 4 load modal-Content from other page [duplicate]

I can't make the Modal work in the remote mode with the new Twitter Bootstrap release : Bootstrap 4 alpha. It works perfectly fine with Bootstrap 3. With bootstrap 4 I am getting the popup window, but the model body is not getting loaded. There is no remote call being made to myRemoteURL.do to load the model body.
Code:
<button type="button" data-toggle="modal" data-remote="myRemoteURL.do" data-target="#myModel">Open Model</button>
<!-- Model -->
<div class="modal fade" id="myModel" tabindex="-1"
role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="modal-title" id="myModalLabel">Model Title</h3>
</div>
<div class="modal-body">
<p>
<img alt="loading" src="resources/img/ajax-loader.gif">
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</div>
Found the problem: They have removed the remote option in bootstrap 4
remote : This option is deprecated since v3.3.0 and will be removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.
I used JQuery to implement this removed feature.
$('body').on('click', '[data-toggle="modal"]', function(){
$($(this).data("target")+' .modal-body').load($(this).data("remote"));
});
According to official documentation, we can do the follow(https://getbootstrap.com/docs/4.1/components/modal):
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
So, I believe this is the best approach (works for BS 5 too):
<!-- Button trigger modal -->
<a data-bs-toggle="modal" data-bs-target="#modal_frame" href="/otherpage/goes-here">link</a>
<!-- Modal -->
<div class="modal fade" id="modal_frame" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<!-- Completes the modal component here -->
</div>
<script>
$('#modal_frame').on('show.bs.modal', function (e) {
$(this).find('.modal-body').load(e.relatedTarget.href);
});
</script>
e.relatedTarget is the anchor() that triggers the modal.
Adapt to your needs
As some of the other answers and Bootstrap docs indicate, Bootstrap 4 requires handling the show.bs.modal event to load content into the modal. This can be used to either load content from an HTML string, or from a remote url. Here's a working example...
$('#theModal').on('show.bs.modal', function (e) {
var button = $(e.relatedTarget);
var modal = $(this);
// load content from HTML string
//modal.find('.modal-body').html("Nice modal body baby...");
// or, load content from value of data-remote url
modal.find('.modal-body').load(button.data("remote"));
});
Bootstrap 4 Remote URL Demo
Another option is to open the modal once data is returned from an Ajax call...
$.ajax({
url: "http://someapiurl",
dataType: 'json',
success: function(res) {
// get the ajax response data
var data = res.body;
// update modal content
$('.modal-body').text(data.someval);
// show modal
$('#myModal').modal('show');
},
error:function(request, status, error) {
console.log("ajax call went wrong:" + request.responseText);
}
});
Bootstrap 4 Load Modal from Ajax Demo
In Asp.NET MVC, this works for me
html
Edit item
<div class="modal" id="modalPartialView" />
jquery
<script type="text/javascript">
function Edit(id)
{
$.ajax({
url: "#Url.Action("ActionName","ControllerName")",
type: 'GET',
cache: false,
data: {id: id},
}).done(function(result){
$('#modalPartialView').html(result)
$('#modalPartialView').modal('show') //part of bootstrap.min.js
});
}
<script>
Action
public PartialViewResult ActionName(int id)
{
// var model = ...
return PartialView("_Modal", model);
}
If you use the Jquery slim version (as in all the Bootstrap 4 docs and examples) the load function will fail
You need to use the full version of Jquery
This process is loading the current dynamic. data remote = "remoteContent.html"
<!-- Link trigger modal -->
<a href="javascript:void(0);" data-remote="remoteContent.html" data-toggle="modal" data-target="#myModal" data-remote="true" class="btn btn-default">
Launch Modal
</a>
This trick : data-remote="remoteContent.html"
<!-- Default bootstrap modal example -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>

Bootstrap Passing Data to a Modal

I have read the Bootsrap documentation and even tested their "Varying modal content based on trigger button" example, but that doesn't work.
Any idea on how can I pass a data to a modal so that I will not create multiple modals in my page.
Here is the button that triggers the modal:
<a class="btn btn-danger" data-toggle="modal" data-target="#deleteSubject" data-whatever="<?= $subj_id ?>" role="button" title="Delete Subject"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a>
And here is the modal:
<div class="modal fade" id="deleteSubject" tabindex="-1" role="dialog" aria-labelledby="deleteSubjectLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="#" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="deleteSubjectLabel">Delete Subject</h4>
</div>
<div class="modal-body">
<h4>Do you want to delete this subject?</h4>
<input type="text" id="subjid" name="subjid">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger">Delete</button>
</div>
</form>
</div>
</div>
</div>
And here is the javascript:
<script>
$('#deleteSubject').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var subjId = button.data('whatever')
var modal = $(this)
modal.find('.modal-body input').val(subjId)
})
</script>
I also tried the show.bs.modal but nothing happens. I tried to create a separate script to test if the $subj_id is being read through the use of alert but it works.
Any ideas?
you need to wrap the code in a document ready and since your input is named and has an id - target it directly and then you wont need the find either:
<script>
$(document).ready(function(){
$('#deleteSubject').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var subjId = button.data('whatever');
$('#subjid').val(subjId);
})
})
</script>
I think you forgot the $ on your modal instance , it should be $modal
<script>
$('#deleteSubject').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var subjId = button.data('whatever')
var $modal = $(this)
$modal.find('.modal-body input').val(subjId)
})
</script>
Simply set the value of input subjid using JavaScript / jQuery during the on click event.
$('#subjid').val(*value*);

Angular-Strap Modal Does Not Load Template

For some reason the modal box works just fine but it does not load any templates I specify.
My Controller has this code;
var brnSearchModal = $modal({ scope: $scope, template: "app/rrn/searchBrn.html", contentTemplate: false, html: true, show: false });
$scope.showModal = function () {
brnSearchModal.$promise.then(brnSearchModal.show);
};
My HTML looks like this;
<button data-ng-click="showModal()" type="button" class="btn btn-info" data-animation="am-fade-and-slide-top">
BRN Lookup
</button>
And my template is in a file and looks like this;
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" ng-show="title">
<button type="button" class="close" ng-click="$hide()">×</button>
<h4 class="modal-title" ng-bind="title">Hello, World!</h4>
</div>
<div class="modal-body" ng-bind="content">Lorem ipsum dolor.</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="$hide()">Close</button>
</div>
</div>
</div>
</div>
There is no error everything seems to be working fine but the template does not load. If I debug angular-strap at one point the template is loaded but then disappears in and leaves a blank modal.
Remove ng-show="title", ng-bind="title" from the template.
Try adding the bs-modal attribute: see examples
<button data-ng-click="showModal()" type="button" class="btn btn-info" data-animation="am-fade-and-slide-top" bs-modal="brnSearchModal">
BRN Lookup
</button>
Otherwise use the data-template attribute directly without using the JS to show the modal:
<button type="button" class="btn btn-info" data-animation="am-fade-and-slide-top" data-template="app/rrn/searchBrn.html" bs-modal="modal">
BRN Lookup
</button>
I think when you put bs-modal="modal" modal is somehow pre-defined in the angular-strap library.
you should remove ng-show="title" , ng-show="content" or ng-bind="title" from the template. You should make sure that the template has no ng-show.
I know it is an old question, but in case others are looking for a solution to the same problem. I found I had to explicitly set templateUrl to falsy when setting template to an html string

jquery modal: closing a modal and then having it available as a clickable option

I been scratching my head on this one for a while.
Writing a plugin in grails that calls on bootstrap-mini.js and most of its css. Everything works fine. The issue I am having is I have a remote form which onComplete runs java script:
https://github.com/vahidhedayati/ml-test/blob/master/grails-app/views/mailingListModal/_modalcreate.gsp
<g:javascript>
function ${controller}CloseModal() {
var myClone=$('#BuildModal${id}').clone();
$('#BuildModal${id}').dialog().dialog('close');
$(".modal-backdrop").hide();
$('body').removeClass('modal-open');
//var myCloner = myClone.clone();
$('#${divId}1').hide().append(myClone);
//$('body').append(myClone);
<g:if test="${!disablecheck.equals('true') }">
var controller="${controller }";
var divId="${divId }";
$.get('${createLink(controller:"MailingListEmail", action: "getAjaxCall")}?ccontroller='+controller+'&divId='+divId,function(data){
$('#${divId}').hide().html(data).fadeIn('slow');
});
</g:if>
}
</g:javascript>
The bits at the top of the function is all the things I have tried so far.
https://github.com/vahidhedayati/ml-test/blob/master/grails-app/views/mailingListEmail/contactclients.gsp
<div class="tbutton">
<button href="#BuildModalSENDERS" class="btn btn-block btn-success" role="button" data-toggle="modal" title="Configure New Sender">
New Sender?</button>
<div id="mailerSenders1">
<g:render template="/mailingListModal/modalcreate" model="[title:'Add Senders Email', controller: 'mailingListSenders', callPage: 'form' , divId: 'mailerSenders', id: 'SENDERS' ]" />
</div>
And finally modelForm which is included on the top of the modalcreate.gsp (now shown)
<div class="modal fade" id="BuildModal${id}" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<g:formRemote id="${controller}" name="urlParams" class="form-horizontal" url="[controller:controller, action:'save']"
update="BuildModal${id}" onComplete="${controller}CloseModal()"
>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">x</button>
<h3>${title }</h3>
</div>
<div class="modal-body">
<div class="form-group">
<g:render template="/${controller }/${callPage }"/>
<g:submitToRemote class="myformsubmit" url="[controller:controller, action:'save']" update="BuildModal${id}" onComplete="${controller}CloseModal()" value="Create" />
</div>
</div>
</g:formRemote>
</div>
</div>
</div>
</div>
So it is a remote Form that submits can calls the above CloseModal
The question is when I Close this how do I make it available again when the user clicks the button to create new email ?
After adding all the cloning at the top of java script the only difference I was able to make was to make it display the backdrop on 2nd click so it went black on 2nd click but did not show up the modal content.
ok got it working by doing this:
<button href="#BuildModalSENDERS" class="btn btn-block btn-success" role="button" data-toggle="modal" title="Configure New Sender"
Now adding
onClick="runCheck()"> .....
<g:javascript>
function runCheck() {
$('#mailerSenders1').show();
}
</g:javascript>
That seems to work fine, it now loads up the page, just to add when I did body it just loaded it up again from the commented out attempts, modal.hide etc did not work and the hide attempts just showed it up under some other layers of the same page.. anyways this works fine now. sorry

Categories