Passing Data-id of an Object to Bootstrap Modal form - javascript

Good day.
I have a task list which has a Delete button in the task field for managing the task.
I am looking how to pass a task parameter containing ID (after pushing a Delete button) to the Bootstrap Modal.
My target is to click the "trash" icon on the task and to show the modal, and only in modal to confirm the deletion.
Here is the button wrapped in modal
`<span data-toggle="tooltip" data-placement="bottom" title="Delete task">
<a data-toggle="modal" data-target="#deleteTaskModal">
<button class="deleteTask far fa-trash-alt" data-id='{id}'></button>
</a></span>`
Here is the modal itself.
I want to use the modal to confirm Deleting the task.
<div class="modal fade" id="deleteTaskModal" tabindex="-1" aria-labelledby="exampleformModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form class="" action="" method="">
<div class="modal-header">
</div>
<div class="modal-body">
<h3>Do you want to delete this task?</h3>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Delete Task</button>
</div>
</form>
</div>
</div>
</div>
</div>
Here is Jquery Script
I tried to catch the ID of the "trigger" and pass it to Modal
$(".modal fade #deleteTaskModal").on('show.bs.modal', function(event) {
var button = $(event.relatedTarget) //Button that triggered the modal
var id = button.data('id');
var url = '/delete/' + id;
if (confirm('Delete task')) {
$.ajax({
url: url,
type: "DELETE",
success: function(result) {
console.log("Deleting task...");
window.location.href = '/';
},
error: function(err) {
console.log(err);
}
})
}
}

You were nearly there though you were not targeting the right element in your modal open.
Since you have an a element and button is inside the a which contains the data-id
You need to watch for the eventTarget and then use .find() method to find the button and get the data id from it which will be passed via ajax
var id = button.find('button').data('id') //need to find the button and get id
In addition, you also need an event handler which will click function inside your modal open which will trigger when you click on Delete task button in your modal.
Lastly I have added a modal close option as well which will happen ajax success - I have fixed up your code and is working as intended.
Live Working Demo: (Showing the data-id in console.log and click button working)
$("#deleteTaskModal").on('show.bs.modal', function(event) {
var button = $(event.relatedTarget) //Button that triggered the modal
var id = button.find('button').data('id') //need to find the button and get id
var url = '/delete/' + id; //url
console.log('data-id= ' + id) //15
//Click delete task in modal
$(document).on('click', '.delete_task', function() {
if (confirm('Delete task')) {
$.ajax({
url: url,
type: "DELETE",
success: function(result) {
$('#deleteTaskModal').modal('hide') //hide modal on success
console.log("Deleting task...");
window.location.href = '/';
},
error: function(err) {
console.log(err);
}
})
}
})
})
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<span data-toggle="tooltip" data-placement="bottom" title="Delete task">
<a data-toggle="modal" data-target="#deleteTaskModal">
<button class="deleteTask fas fa-trash-alt" data-id='15'></button>
</a>
</span>
<div class="modal fade" id="deleteTaskModal" tabindex="-1" aria-labelledby="exampleformModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form class="" action="" method="">
<div class="modal-header">
</div>
<div class="modal-body">
<h3>Do you want to delete this task?</h3>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary delete_task">Delete Task</button>
</div>
</form>
</div>
</div>
</div>
</div>

Related

How to detect the way Bootstrap modal is closed

I'm attaching handler to the Bootstrap hidden.bs.modal event to detect when the modal is closed, but it can be closed in multiple ways:
Explicitly close it via$('#modal').modal('hide') or $('#modal').modal('toggle');
Clicking on modal's backdrop part (if allowed);
Via data attributes e.g. data-dismiss="modal"
Is there a way to detect which of the options was used? Inside the hidden.bs.modal handler e.target always appears to be div#modal
The thing is that hidden.bs.modal is an event that fires once the modal has been closed. So that is not the click event the user triggered from the close button, the corner X or the overlay...
That said, you can use the click event to store where the user clicked in a variable and milliseconds after, when the hidden.bs.modal fires, use the variable.
Demo:
$(document).ready(function(){
// Variable to be set on click on the modal... Then used when the modal hidden event fires
var modalClosingMethod = "Programmatically";
// On modal click, determine where the click occurs and set the variable accordingly
$('#exampleModal').on('click', function (e) {
if ($(e.target).parent().attr("data-dismiss")){
modalClosingMethod = "by Corner X";
}
else if ($(e.target).hasClass("btn-secondary")){
modalClosingMethod = "by Close Button";
}
else{
modalClosingMethod = "by Background Overlay";
}
// Restore the variable "default" value
setTimeout(function(){
modalClosingMethod = "Programmatically";
},500);
});
// Modal hidden event fired
$('#exampleModal').on('hidden.bs.modal', function () {
console.log("Modal closed "+modalClosingMethod);
});
// Closing programmatically example
$('#exampleModal').modal("show");
setTimeout(function(){
$('#exampleModal').modal("hide");
},1000);
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
CodePen
You can use the hide.bs.modal event to capture the document.activeElement. If you have multiple buttons all of which include data-bs-dismiss='modal', this will allow you to determine which of those buttons was pressed. This avoids the need for onclick= approaches or additional event handlers.
It seems it would be more elegant if the Event object for the hide.bs.modal event had a .relatedTarget or similar which contained the triggering element, but alas that's not the case right now.
The example below assumes jQuery with $:
$(() => {
var $dlg = $("#myBootstrapModalDialog");
var $closeElement;
$dlg.on('show.bs.modal', (e) => {
// maybe do something to initialize the modal here...
})
.on('hide.bs.modal', (e) => {
$closeElement = $(document.activeElement);
})
.on('hidden.bs.modal', (e) => {
var id = $closeElement.attr('id');
// do something depending on the id...
if (id === 'btn-save') {
// save something
}
$closeElement = null;
});
});
Sample HTML:
<div class="modal fade"
id="myBootstrapModalDialog"
tabindex="-1"
aria-labelledby="myDialogTitle"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content rounded-0 mx-auto">
<div class="modal-header">
<h3 class="modal-title text-primary" id="myDialogTitle">
Save this stuff?
</h3>
<button id="btn-close" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body px-3">
Are you sure you want to save this stuff?
</div>
<div class="modal-footer">
<button id="btn-cancel" type="button" class="btn btn-link" data-bs-dismiss="modal">
Cancel
</button>
<button id="btn-save" type="button" class="btn btn-secondary" data-bs-dismiss="modal">
Save
</button>
</div>
</div>
</div>
</div>

Bootstrap modal - Modal closing immediately on click

I am trying to do a GET request to server and populate the modal with data from database. I am trying to make it like a API so that it is easier for me in the future.
By adding showAjaxModal class to all anchor tags, I am trying to automatically load the modal and do an ajax request to the href attribute of the anchor tag.
However, upon doing so, it all works but the modal immediately disappears and I get this error message:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
JS Fiddle: https://jsfiddle.net/43jj3q30/
Code:
<a class="btn btn-primary showAjaxModal" data-toggle="modal" href="/api/path-to-request" data-target="#modal-id">Trigger modal</a>
Modal:
<div class="modal fade" id="modal-id">
<div class="modal-dialog">
<div id="modal-loading-icon"></div>
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
Modal body ...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
My Ajax code:
$('.showAjaxModal').click(function (event) {
var loadingIcon = $('.modal-loading-icon');
var ajaxUrl = $(this).attr('href');
$.ajax({
url: ajaxUrl,
beforeSend: function () {
loadingIcon.show();
}
}).success(function (data) {
event.preventDefault();
loadingIcon.hide();
// $('.modal-body').html(data);
$('.modal-body').html('test');
});
});
What exactly am I doing wrong here? Please help.
Thank you!
change your link to:
<a class="btn btn-primary showAjaxModal">Trigger modal</a>
and add
$('#modal-id').modal('show'); //add this line to your success callback
-
success(function (data) {
event.preventDefault();
$('#modal-id').modal('show'); //add
loadingIcon.hide();
// $('.modal-body').html(data);
$('.modal-body').html('test');
});
working demo: https://jsfiddle.net/43jj3q30/3/

jquery accessing data-attrs

I'm using bootstrap modal for destroying task objects. When I click on a given task on the index page the modal window pops up and the destroy link of that task gets loaded via data attr, so modal will know which task should be destroyed when user clicks on #delete-task-submit button.
The code works as it is, but I'd like to use data-behavior="delete-task-submit" instead of #delete-task-submit to be clear that this has nothing to do with styling and it's only there for the js call.
What's the right way to do it? I'm asking this because #delete-task-submit is used in the first js call for finding/setting data-task-destroy-link and don't know how else I can find that data attribute without adding id/extra class there.
<div class="modal fade" id="delete-task-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content" style="text-align:left">
<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">Delete Task</h4>
</div>
<div class="modal-body">
<h4>Are you sure?</h4>
<p> </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deletetaskclose">Close</button>
<a href="#" id="delete-task-submit" type="button" class="btn btn-danger" data-task-destroy-link >Delete Task</a>
<!-- DESTROY LINK GETS INSERTED HERE -->
</div>
</div>
</div>
</div>
$(document).on('click', '[data-behavior="open-delete-task-modal"]', function (event) {
var taskDeleteLink = $(this).data("task-delete-link");
$('#delete-task-submit').data("task-destroy-link", taskDeleteLink);
});
$(document).on('click', '#delete-task-submit', function (event) {
var href = $(this).data("task-destroy-link");
$.ajax({
type: "DELETE",
url: href,
dataType: "script"
});
});
I'm asking this because #delete-task-submit is used in the first js call for finding/setting data-task-destroy-link and don't know how else I can find that data attribute without adding id/extra class there.
Replace $('#delete-task-submit') with $('[data-behavior="delete-task-submit"]') selector in that part of your code and add data-behavior="delete-task-submit" attribute to your link.
Delete Task

bootstrap modal prevent rightclick

I try to preventDefault on mouse-rightclick and it works fine until I try to open a bootstrap modal.
If I use "alert" og do nothing the rightclick is prevented, but when I open a bootstrap modal it is not. I've tried to google it, but I can't find my answer.
$(".timer").on("contextmenu", function(evt) {evt.preventDefault();});
$(".timer").mousedown(function(e){
// $(".timer").bind('contextmenu', function(){ return false });
e.preventDefault();
if( e.button == 2 ) {
e.preventDefault();
$('#changeTime').modal('show'); // rightclick is NOT prevented.
// alert('Hello'); // this works...?
return false;
}
return true;
});
Can anyone please help me? Thanks.
The php is:
echo '<td class="description" name="id' . $todos->id . '">
<span class="descriptionText'.$todos->id.'">'
. $todos->description . '</span></td><td style="width:50px;">
<span class="timer pull-right btn btn-primary" name="id'.$todos->id.'">
' . show_time($todos->total_time) . '</span></td></tr>';
The HTML modal is:
<div class="modal fade" id="changeTime" 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"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Change time</h4>
</div>
<div class="modal-body">
<form>
// A lot of HTML :)
</form>
</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>
So based on the comments below, I think I should update my answer.
You wanted to ignore a default click and allow a modal to show up using the right click instead.
In order for that to happen, you need to block all of the things that a default click would do using preventDefault() and stopPropagation()
$("[data-toggle='modal']").click(function (e) {
e.preventDefault();
e.stopPropagation();
});
After that you want to bind the modal opening function to the right click event, but don't show the context menu.
$("[data-toggle='modal']").on("contextmenu", function(e) {
e.preventDefault(); // don't show the context menu
$("#changeTime").modal("show"); // show the modal window
})
Here's a CodePen of it working

jQuery Submit is not working?

I used modal of bootstrap and when i click Add Changes button, nothing happens.. :(
Script in head:
<script>
$("addBtn").click(function() {
$("programFormDropDown").submit(function(event) {
});
});
</script>
My modal in body:
<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-hidden="true">×</button>
<h4 class="modal-title">Confirm your change</h4>
</div>
<div class="modal-body">Are you sure you need to add these ?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="addBtn" class="btn btn-primary">Add changes</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
and my form in same body
<form id="programFormDropDown" action="../hDashBoard/project">
.....
can you give some idea?
You seem to have forgoten a # in your selectors, unless you are using Mootools which gets the ID with $('id') try this:
$("#addBtn").click(function() {
^
$("#programFormDropDown").submit(function(event) {
^
});
});
You seem to be missing the '#' reference from your selector.
<script>
$("#addBtn").click(function() {
$("#programFormDropDown").submit(function(event) {
});
});
</script>
you have miss # in two selector jquery
try this:
$("#addBtn").click(function() {
$("#programFormDropDown").submit(function(event) {
});
});
instead of this:
$("addBtn").click(function() {
$("programFormDropDown").submit(function(event) {
});
});
Looks like you are not looking for ajax submit, in that case change the button type to submit like
<button id="addBtn" class="btn btn-primary" type="submit">Add changes</button>
if you want to use script
/add script in dom ready handler
jQuery(function () {
//use id selectors - # in front of id
$("#addBtn").click(function () {
//call the dom elements submit method
$("#programFormDropDown")[0].submit();
});
})

Categories