Get e.relatedTarget when using Twitter Bootstrap modal buttons - javascript

I have written the code to show a modal when a button is clicked, with the intention to edit button's text inside the modal.
My intention is to have a lot of buttons, so instead of getting them by id, I use e.relatedTarget when the modal is invoked in order to know which button has called and get the text from the button so I can show it at the modal.
But the problem comes when I edit the text at the modal and click the OK button. I don't know how to access the e.relatedTarget from there.
HTML:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Change this text</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" 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="exampleModalLabel">New message</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="text-to-edit" class="control-label">Edit text:</label>
<input type="text" class="form-control" id="text-to-edit">
</div>
</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">Send message</button>
</div>
</div>
</div>
</div>
JS:
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var buttonText = button.text() // Get text
// 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-body input').val(buttonText)
});
// Modal ok button
$('#exampleModal .btn-primary').click(function() {
// Get input text value
var text = $('#exampleModal').find('.modal-body input').text();
// Hide modal
$('#exampleModal').modal('hide');
// Set new text to the caller button
// ?
});
JsFiddle: http://jsfiddle.net/nm4nmxsf/
Any help?

I added comments showing you what to change
// Set an empty variable for button outside of your function !important
var button = '';
$('#exampleModal').on('show.bs.modal', function (event) {
//don't redeclare your variable for button, instead update it
button = $(event.relatedTarget) // Button that triggered the modal
var buttonText = button.text() // Get text
// 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-body input').val(buttonText);
});
// Modal ok button
$('#exampleModal .btn-primary').click(function() {
// Get input text value
//use val() instead of text()
var text = $('#exampleModal').find('.modal-body input').val();
$('#exampleModal').modal('hide');
// Set new text to the caller button
// ?
button.text(text);
});
See this fidde:
http://jsfiddle.net/nm4nmxsf/4/

var button;
$('#exampleModal').on('show.bs.modal', function (event) {
button = $(event.relatedTarget);
var buttonText = button.text();
var modal = $(this);
modal.find('.modal-body input').val(buttonText);
});
$('#exampleModal .btn-primary').click(function() {
var text = $('#exampleModal').find('.modal-body input').val();
$('#exampleModal').modal('hide');
button.text(text);
});
JSFIDDLE

Related

How to toogle different modal with different content and change the button as well?

I wanna toggle different models and calculate the results in form individually.
I try to avoid paste too many modal codes and found the sample HERE, however, it use the same ID, so I get stuck!
If you click on
Button A it shows Modal A with Calculate A.
Button B it shows modal B with Calculate B.
Button N it shows modal N with Calculate N.
Is there a way to change the button to another one? or any help?
Much appreciate!
$('#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('Form click on ' + recipient)
modal.find('.modal-body input').val(recipient)
$("#buttonA").click(function () {
var a = $("#amout").val();
alert("Results: " + a);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button A">Run button A</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button B">Run button B</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button N">Run button ...N</button>
<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">Form 1-N</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
Num: <input id="amout" type="number">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="buttonA">calculate</button>
</div>
</div>
</div>
</div>
The Fastest way is set id for each button you want change and Change innerText of that in your Function.
Html Tag
<button id="AcceptBTN" type="button" class="btn btn-primary">Send message</button>
^
|
Here
jQuery
$('#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.
$('#AcceptBTN')[0].innerText = recipient; <-----------------Here
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
GoodLuck

How to create a click-function in a modal

Hey I am new to js and I was trying to open a bootstrap modal with a click on a button (I set the id to the value of the button because the id comes from a database) and if you click on "yes" in that modal a click function should be triggered which should then delete the selected row.
I am able to open the modal and setting the id also works but if I click the yes button in the modal there is no alert...
This is the modal located in content.html:
<!--Delete Modal-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="exampleModalLabel">Return Device</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col">
<p><b> Are you sure you want to return this device? </b></p>
Please make sure you return the device.
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">No</button>
<button type="button" class="btn btn-primary delBtn" data-dismiss="modal">Yes</button>
</div>
</div>
</div>
</div>
This is my JS located in main.js:
$(document).ready(function () {
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').trigger('focus');
});
$('#booked').click(function () {
$('#changestuff').load('content.html #booked', function () {
register();
change();
$('.ret').click(function () {
var id = $(this).val();
var tr = $(this).closest('tr');
})
returnOne(id, tr);
});
$('#booked').addClass('active');
$('#book').removeClass('active');
$('#admin').removeClass('active');
});
});
function returnOne(id, tr)
{
$('.delBtn').click(function () {
alert("you returned" +id);
})
}
Where is my error? I think it might be because the modal hasn't been loaded when I try to get the click event but I'm not sure. Thanks in advance!
click event handler is not attaching may be it is getting called before yes button dom get created.
Try below code where you can store row to be deleted in a variable and set row-id data attribute on Yes button. In click handler of Yes button, read the id and you can delete row from variable rowToDelete
$(document).ready(function(){
var rowToDelete;
$('#myModal').on('shown.bs.modal', function(){
$('#myInput').trigger('focus');
});
/*$('#changestuff').load('content.html #book', function(){
register();
change();
getChosenDevices();
});*/
$('#changestuff').on('load','content.html #book', function(){
register();
change();
getChosenDevices();
});
$('#booked').click(function() {
$('#booked').addClass('active');
$('#book').removeClass('active');
$('#admin').removeClass('active');
});
$(document).on('click','.ret',function() {
var id = $(this).val();
$('#deleteModal .delBtn').data('row-id', id); //set data id
rowToDelete = $(this).closest('tr'); //store row in variable
});
$(document).on("click", '#deleteModal button.delBtn', function(e) {
e.preventDefault();
var rowId = $(this).data('row-id');
alert("you returned" + rowId);
$('#deleteModal').modal('toggle');
});
});
JSFiddle Demo

Pass a variable from a function to another in jQuery

I'm a newbie in Javascript world, and I searched a lot for a similar question but never worked for me.
So I'm working with a Bootstrap modal, I have 3 buttons with different names that opens a modal window.
When I close the modal window I want an alert that show me the name of the button I've clicked.
For example, if I click on the button "Email Ted", when I close the modal the alert will say "You haven't sended the message to Ted".
I get the names from the attribute data-name="" in every button.
I also tried to insert the first function in a global variable, but didn't worked; so the code below is an idea to what I want to do.
$(document).ready(function() {
$("#exampleModal").on('show.bs.modal', function(e) {
var button = $(e.relatedTarget);
var recipient = button.data('name');
var modal = $(this);
modal.find('.modal-title').text('New message to ' + recipient);
return String(recipient);
});
$('#exampleModal').on('hidden.bs.modal', function(recipient) {
alert('The message will not be sended to ' + recipient);
});
});
Thanks!
I made a working demo out of what I understand of your question.
Please have a look and ask for what you need to be explained.
$(document).ready(function() {
$("#open").on("click",function(){
$("#exampleModal").modal("show");
});
var recipient="";
$("#exampleModal").on('show.bs.modal', function(e) {
recipient = $("#open").data('name');
var modal = $(this);
modal.find('.modal-title').text('New message to ' + recipient);
return String(recipient);
});
$('#exampleModal').on('hidden.bs.modal', function() {
alert('The message will not be sended to ' + recipient);
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<div class="modal" tabindex="-1" role="dialog" id="exampleModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">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">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal" data-name="TEST Name">Close</button>
</div>
</div>
</div>
</div>
<button id="open" data-name="John Doh">Open modal</button>
First of all it is important to mention that your snippet is not just general JavaScript, but the way Twitter Bootstrap works. There are no native shown and hidden events.
So you have custom events here. Btw. referring to the bootstrap reference, it should be shown.bs.modal (recognize the missing 'n' in your code) or maybe I am wrong and they made some changes.
You could safe the button name in a variable like so:
$(document).ready(function() {
var recipient = null;
$("#exampleModal").on('shown.bs.modal', function(e) {
var button = $(e.relatedTarget);
var modal = $(this);
recipient = button.data('name');
modal.find('.modal-title').text('New message to ' + recipient);
});
$('#exampleModal').on('hidden.bs.modal', function(recipient) {
if (recipient) {
alert('The message will not be sended to ' + recipient);
recipient = null; // important to reset this var for a second trigger
}
});
});

Javascript waiting result of modal

I have a simple question about javascript and bootstrap modal. I have a wizard where I use file upload form, so I check the name of the file and if it doesn't contains some string I have to show a modal where ask if you want to continue anyway. How can I know which button is clicked into modal from javascript or jquery?
I have this code:
if (index==3){
var fileControl = document.getElementById('file');
//Check if the datatable name contains idFLeet and IdCar. REturn -1 if it not contains the string
if (fileControl.files[0].name.indexOf($("#selectedFleet").val()) > -1 && fileControl.files[0].name.indexOf($("#selectedCar").val()) > -1){
//File contains id so you can continue the upload
uploadFunction();
}
else{
$('#warningDatatableModal').modal("show");
//If click on Yes call uploadFunction
//If click on No return false
}
}
HTML modal code:
<div class="modal" id="warningDatatableModal" data-backdrop="static" data-keyboard="false">
<div class="modal modal-warning">
<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">Warning</h4>
</div>
<div class="modal-body">
<p>There is a incongruity between file name and fleet and
car previously selected. Are you sure to continue?</p>
</div>
<div class="modal-footer">
<button id="close" type="button" class="btn btn-outline pull-left"
data-dismiss="modal">Close</button>
<button id="continueButton" type="button" class="btn btn-outline">Continue</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
</div>
After Yeldar Kurmangaliyev advice I have update my code but the wizard go ahed to the next tab instead of waiting into actual tab
if (index==3){
var fileControl = document.getElementById('file');
//Check if the datatable name contains idFLeet and IdCar. REturn -1 if it not contains the string
if (fileControl.files[0].name.indexOf($("#selectedFleet").val()) > -1 && fileControl.files[0].name.indexOf($("#selectedCar").val()) > -1){
//File contains id so you can continue the upload
uploadFunction();
}
else{
$('#warningDatatableModal').modal("show");
$(".modal-footer > button").click(function() {
clicked = $(this).text();
$("#warningDatatableModal").modal('hide');
});
$("#warningDatatableModal").on('hide.bs.modal', function() {
if (clicked === "Cancel"){
return false;
}else {
uploadFunction();
}
});
}
}
If I put this code out of wizard works(it doesn't close modal with cancel button because I use return false that needs for my wizard), but I need to stop wizard waiting modal result.
You can simply attach events to your buttons.
However, the user may want to close the window without action. The design of modal UI and its overlay suggests to click outside the window and close it.
In order to create an event which will fire event always when a user closes your modal, you need to attach to hide.bs.modal event:
$('#warningDatatableModal').on('hide.bs.modal', function() {
});
Here is the working JSFiddle demo.
You can try using the ids of the buttons and attaching a listener to see when they have been clicked like so:
$('#close').on('click',function(){
//do something
});
$('#continueButton').on('click',function(){
//do something
});

Bootstrap modal not closing after form submission

I believe I will get a solution here, bootstrap modal does not disappear after form submission. I only want to make bootstrap modal disappear after form submission and when again button is clicked (without refreshing the page) form should open, send data and modal should disappears and so on... This is it !
Here is a bootstrap modal:
<div class="modal fade myPopup" id="basicModal" tabindex="-1" role="dialog"
aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog" id="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" id="myModalLabel">Add New Board</h4>
</div>
<div class="modal-body">
<form class="create_Category_board" id="myform">
<input type="text"
id="customInput"
class="board_name"
name="board[name]"
placeholder="Board Name ..." />
<input type="text"
class="board_description"
name="board[description]"
placeholder="Board Description ..." />
<input type="hidden"
class="board_description"
id="myCid"
name="board[category_id]" />
<input type="submit" value="Create Board" class="ShowFormButton"/>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
My form is bound with backbone JS function:
events: {
"submit form.create_Category_board": "createCategoryBoard"
},
createCategoryBoard: function(event) {
event.preventDefault();
var that = this;
// get form attrs, reset form
var $form = $(event.target);
var attrs = $form.serializeJSON();
$form[0].reset();
var board = new Kanban.Models.Board();
// fail if no board name
if (!attrs.board.name) {
var $createContainer = $("div.create_board");
var $nameInput = that.$el.find("input.board_name");
$createContainer.effect("shake", {
distance: 9,
times: 2,
complete: function() {
$nameInput.show();
$nameInput.focus();
}
}, 350);
return false;
}
attrs.board.category_id = myid;
var category = Kanban.categories.get(myid);
var boards = category.get("assigned_boards");
// save list
board.save(attrs.board, {
success: function(data) {
board.get("users").add(Kanban.currentUser);
boards.add(board);
// keep focus on list input
that.$el.find("input.board_name").focus();
}
});
$('#basicModal').modal('hide');
}
As a last line in above function I have tried most popular solution $('#basicModal').modal('hide'); available on web! It makes my modal look like this:
i.e. it not hides the modal, moreover make screen black and change the direction of bootstrap modal from center of screen to little right. May be it is overridden by CSS of JS. But I am not sure.
I am posting my own answer because if some one needs a quicker help, then may be it is helpful:
Just replace: $('#basicModal').modal('hide'); with this line:
$(".modal-header button").click(); which is last line of my JS function.
Cheers :)
Problem is that div.modal-backdrop remains after you hide the modal,
you can see it in developer tools.Try simple remove
$('#basicModal').modal('hide');
$('.modal-backdrop').remove();
Cheers

Categories

Resources