Send data from an index to a bootstrap modal - javascript

I'm trying to send data from my index page to a modal.
Here's my code.
Modal
<div class="modal modal-1 fade bd-example-modal-lg " id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title subtitles" id="exampleModalLongTitle">¿Cómo funciona?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="demo">
<!-- Here's where I want to get data -->
<input data-id="sum">
</div>
</div>
<div class="modal-footer">
<!-- <button type="button" class="btn btn-secondary" data-dismiss="modal"></button> -->
<button type="button" class="btn btn-secondary" data-dismiss="modal" data-toggle="modal" data-target="#exampleModalCenter2" >Siguiente</button>
</div>
</div>
</div>
</div>
First, my button to show my modal
<button type="button" data-toggle="modal" data-target="#exampleModalCenter" > Cotizar préstamo </button>
Input data that I want to send to my modal
<input class="c-slider__loan-sum" id="sum" name="loan_sum" type="hidden" value="NaN">
<input class="c-slider__loan-period" name="loan_period" type="hidden" value="20">
And I've been trying with this jQuery
$('#exampleModalCenter').on('click','shown.bs.modal', function () {
let a = $(this).data('id');
$(".modal-body #sum").val( a );
$('#myInput').trigger('focus');
})
If someone could help me, I'll be so grateful

I believe your argument list for .on() is incorrect. If you want to specify multiple events to trigger the handler you separate them with a comma: .on('click, shown.bs.modal', func...).
However, I think you need to remove shown.bs.modal all together, as that event is triggered after the modal has rendered.
Another issue you may have is that you're not actually getting the values from your hidden inputs in your handler. You're just, seemingly, trying to get the id of the button that's being clicked and setting that as the value on some non-existent input in your modal. If you are trying to get the id of the button (for some reason I can't see) then you can get it like this const id = $('#buttonId').attr('id');. What you're doing is trying to get the value from a data attribute that doesn't exist on the button element: ...').data('id');.
Check out this simple example to see how you may want to handle this: https://codepen.io/dustinoverby/pen/NExXMb?editors=1010

Related

Performance and Optimization - Too many bootstrap modals

I am building a table based on data returned from my API.
For each row in the table I would like to create a bootstrap modal with additional info in it.
This is how I do it right now. I created a designated div and I put all the modals inside it. Please note that in addition the modal's HTML is pretty big by itself:
let modal = `<div id="modal-${i}">big HTML here</div>`;
$("#modalsCollector").append(modal);
And this is how my table row looks like:
<tr data-toggle="modal" data-target="#modal-${i}">
Because I sometimes have 500+ table rows there is eventually a huge div (#modalsCollector) full of same (by structure) modals. I feel that it affects page performance.
Is there a better, more elegant and performance optimized way to bind modals to table rows? Or in general, working with many hidden elements instead of pushing them into the DOM that way?
You can include only one "null" modal in your <body>, like this:
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Then when you have to show the modal generate it using jQuery like this:
$("#button").click(function(e){
$("#myModal .modal-header").append(HTML for modal header here);
$("#myModal .modal-body").html(big HTML for modal body here);
$("#myModal").modal("show");
});
So, basically you change the modal header and the modal body of the same modal each time, with the needed information accordingly, without the need of like thousands of modals.
Bootstrap has a neat way of changing the components of the same modal. This is as long as you need the same modal just different content inside.
https://getbootstrap.com/docs/4.5/components/modal/#varying-modal-content
Here is an example:
HTML:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="#mdo">Open modal for #mdo</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="#fta">Open modal for #fat</button>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Recipient:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
and 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
// Update the modal's content.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})

Display Bootstrap Modal using javascript onClick

How do I add a bootstrap modal in the the javascipt on click. So far I was only able to alert ("hello") on click. How do i prompt out a modal box?
graph.on("click", function (params) {
var node = params['nodes'][0];
displayInfo=false;
if(node!=null){
console.log('node:'+ params['nodes'][0]);
x = params["pointer"]['canvas']['x'];
y = params["pointer"]['canvas']['y'];
displayInfo=true;
lastNode = nodes.get(node);
lastClick = params['pointer'];
//console.log(node);
}
alert("hello");
//add boostrap modal here
});
You don't need an onclick.
<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>
<div id="GSCCModal" class="modal fade" 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" 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>
If you need an onclick event anyhow, use it like below:
graph.on("click", function (params) {
$('#myModal').modal('show');
}
Reference: http://getbootstrap.com/javascript/#modals
Create modal HTML and assign id for it, for example "my_modal"
http://getbootstrap.com/javascript/#live-demo
show the modal at the js using the code:
$("#my_modal").modal('show');
First make the modal pop up div then , Configure and use .modal('show')
For eg:-
You can also use onClick call for jquery here.
<div id="modalDiv">
//some content
</div>
In jquery use ,
$("#modalDiv").modal('show');
Check this http://getbootstrap.com/javascript/#live-demo
You can use id like
$("#modal-id").modal("show");
Or you can use class name $(".modal-class").modal("show");

Onclick function triggering multiple times

I am having an issue when saving inside of the add-comment modal. When I click on "save" inside of the modal it is triggers depending on how many times I have previously opened that modal.
The form I am working with is dynamic so there could be 1 to many comments to be added. I only want to use one modal to insert comments in a hidden field (not shown)
I am very confused to why when i click on the
TEST CASE
Launch Page
Open the comment modal using the comment icon
Click Save
Repeat open and saving the comment modal multiple times.
Look inside of console to see
"In Save Comment: " + i
Where i equals the number of times it is in that function.
HTML
<form id="requestForm">
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#detailsModal"><span class="glyphicon glyphicon-share" aria-hidden="true"></span></button>
<button type="button" class="btn btn-default" data-add-comment><span class="glyphicon glyphicon-comment" aria-hidden="true"></span></button>
</form>
<div class="modal fade" id="detailsModal" tabindex="-1" role="dialog" aria-labelledby="detailsModalLabel">
<div class="modal-dialog" role="document">
<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="detailsModalLabel">User Details</h4>
</div>
<div class="modal-body">
<table class="table table-bordered">
<tbody>
<tr>
<td class="col-sm-3"><strong>Name</strong></td>
<td class="col-sm-4" id="info-name"></td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- End Details Modal -->
<!-- Comments Modal -->
<div class="modal fade" id="commentModal" tabindex="-1" role="dialog" aria-labelledby="commentModalLabel">
<div class="modal-dialog" role="document">
<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="commentModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<textarea id="modalComTxt" class="form-control" rows="4" maxlength="512"></textarea>
<p>Characters left: <span id="txtAreaCount">512</span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="save-comment" type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
JAVASCRIPT
$("#requestForm").on('click', '[data-add-comment]', function() {
var curComBtn = $(this);
var curComment = curComBtn.prev().val();
var modalTxt = $('#modalComTxt');
var commentModal = $('#commentModal');
modalTxt.val(curComment); //set the modal value with existing comment
var i = 1;
$('#txtAreaCount').text((512 - modalTxt.val().length)); //change text count in modal
commentModal.modal('toggle');
//Function when clicking save in modal
$('#save-comment').click(function() {
console.log("In Save Comment: " + i)
i++
console.dir(curComBtn.prev());
curComBtn.prev().val(modalTxt.val());
});
});
Move the code below outside the $("#requestForm").on('click', function(){...} handler. What is happening, is that you bind an additional handler to save-comment button click event every time the [data-add-comment] button of the form gets clicked.
$('#save-comment').click(function() {
var curComBtn = $('#requestForm').find('[data-target="#detailsModal"]');
curComBtn.val( $('#modalComTxt').val() );
});
Every time someone clicks #requestForm you bind the click eventlistener to #save-comment. So after opening the modal for a second time there will be two click eventlisteners binded to #save-comment.
Since #save-comment isn't added dynamically, you can bind the click event outside of the #requestForm click handler:
$('#requestform').click(function(){
// do stuff
});
$('#save-comment').click(function(){
// do other stuff
});

jQuery append() not working inside a bootstrap modal

I have a bootstrap modal as following:
<div class="modal fade" id="container-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="false">
<div class="modal-dialog" role="document">
<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">
<ul class="modal_containers" id="list_ctns">
<li><img src="images/container.png"></li>
<li><img src="images/container.png"></li>
<li><img src="images/container.png"></li>
</ul>
</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>
The above modal is triggered when a particular button is clicked which can be considered as a repository of certain elements.
I have a form which has a submit button. On clicking that submit button, I want to append a list item to the modal_body.
<div class="button-containers">
<button class="btn btn-success" id="save_item" type="submit">Save</button>
</div>
So, I wrote this simple javascript snippet to append the list item to the modal.
$(document).ready(function(){
$('#save_item').click(function(e){
$("#list_ctns").append("<li><img src="images/container.png"></li>")
});
});
I am not sure, where I am making a mistake. Please help me with your suggestions.
Cheers,
SZ
Mind the quotes when you pass that as a string to set a value.
"<li><img src="images/container.png"></li>"
should be either
"<li><img src='images/container.png'></li>"
or
"<li><img src=\"images/container.png\"></li>"
Also don't forget to prevent the default action of the submit button.
$('#save_item').click(function(e) {
e.preventDefault();
$("#list_ctns").append("<li><img src='images/container.png'></li>")
});
The button type is submit so when you click it, the form will submit causing the page to be redirected to the "action" url.
You can create a JS function to handle it like this;
function handleModal(form)
{
$("#list_ctns").append("<li><img src=\"images/container.png\"></li>");
//Use $.AJAX() to submit the form without refreshing the page.
return false; //this prevent the form from being submitted. Keep it if you are going to use $.AJAX() to submit the form or remove it if you want the form to submit normally.
}
and then call it from the <form> node by adding onsubmit="return handleModal(this);" attribute to it.

jQuery - Event not working properly

I'm setting a click event on an anchor to set a value to a button (initially, the button has a -1 value, that can't be submitted) that later will submit an Ajax call. The problem is that sometimes it works, sometimes doesn't; I just don't understand why.
JS:
$(".events-list a").click(function(e) {
e.preventDefault();
var id = $(this).data('event-id');
$(".edit-occurrence-button").val(id);
});
HTML:
<div id="modal-edit-occurrence-form" class="modal hide fade" tabindex="-1" style="font-family: 'Open Sans', sans-serif;" role="dialog" aria-labelledby="modal-edit-occurrence-label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="modal-edit-occurrence-label">Editar ocorrência</h3>
</div>
<div class="modal-body">
<form>
<fieldset>
<!-- Some input fields here -->
</fieldset>
</form>
</div>
<div class="modal-footer">
<button id="modal-edit-occurrence-submit" class="btn btn-info">Editar</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancelar</button>
</div>
</div>
<div class="modal hide fade" id="events-modal">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Ocorrência</h3>
</div>
<div class="modal-body" style="height: 600px;">
<!-- Some content here -->
</div>
<div class="modal-footer">
<button class="btn btn-info edit-occurrence-button" value="-1" data-dismiss="modal" aria-hidden="true">Editar</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Fechar</button>
</div>
</div>
OBS: The .events-list a is an anchor generated by BootstrapCalendar dynamically (http://bootstrap-calendar.azurewebsites.net/), that has this format:
<div class="events-list" data-cal-start="1386126000000" data-cal-end="1386212400000">
</div>
EDIT: I found out why it doesn't work sometimes. It deppends on what element is triggering the event. On Bootstrap Calendar, we have 3 ways of openning the calendar event (clicking the event on the calendar, clicking the event after opening the day's events, clicking on the last events). The problem is only when I try to click on the event after opening the day's events, because it is generated dynamically. How can I fix it?
The problem is that jquery can't see the element and attach a event handler.
Try using the jquery .on() event handler
$("##static_parent##").on('click' , '.events-list a', function(e) {
e.preventDefault();
var id = $(this).data('event-id');
$(".edit-occurrence-button").val(id);
});
Replace ##static_parent## with a parent element of your target element that's rendered in the page on load. (if you can't find any use 'body').
This might be useful
Try preventing default event for <a> also with some code refactoring
$(".events-list a").click(function(e) {
e.preventDefault();
var id = $(this).data('event-id');
$(".edit-occurrence-button").val(id);
});
Assuming the HTML looks like below
<input type="submit" class="edit-occurrence-button" value="1" />
<ul class="event-list">
<li>Event
</a>

Categories

Resources