jQuery - Event not working properly - javascript

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>

Related

Block the "show" event when my modal is already open (the script reloads)

I use a modal to dynamically load content to the user (thanks to AJAX and the link he clicked)
On one of the Ajax pages that I load I added a date field with the bootstrap-datepicker plugin (https://bootstrap-datepicker.readthedocs.io/en/latest/)
The problem is that when I click on the input to add the date, it is as if the modal is reloading and I cannot block it
I created a simple example to show the problem (but suddenly on my site, when I click on the date field, it reloads the page at AJAX)
http://jsfiddle.net/1L32hyzt/
HTML:
<!-- 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">
<input type="text" name="date_from" class="form-control date-test date-from" placeholder="" value="" autocomplete="off">
</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>
Javascript:
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var modal = $(this)
//......
console.log('MODAL SHOW')
$('.date-test').datepicker();
$('.modal-body').prepend('<div><strong>MODAL SHOW</strong></div>')
});
As you can see, when we click on this input, it reloads the script and adds "MODAL SHOW" again
I tried to add modal.off(); in the modal script like this:
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var modal = $(this)
//......
modal.off();
console.log('MODAL SHOW')
$('.date-test').datepicker();
$('.modal-body').prepend('<div><strong>MODAL SHOW</strong></div>')
});
But the problem is that if the user closes the modal and clicks on another link, it reloads the same modal as the old one (whereas it is another link with another data)
Where does the problem come from ?
How to make sure that when I click on the input, the script does not think that I am reloading the modal
Adding the following code should help with your problem.
$(".date-test").datepicker().on('show.bs.modal', function(event) {
// prevent datepicker from firing bootstrap modal "show.bs.modal"
event.stopPropagation();
That's a known bug hat has to do with bootstraps datetimepicker
https://github.com/uxsolutions/bootstrap-datepicker/issues/978

Send data from an index to a bootstrap modal

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

Submitting form data from modal, modal won't close

I'm creating a type of content management system that allows users to create pages based on templates.
I have a page that has 2 placeholder divs. Below is an example of one. When you click on the div, a modal pops up that allows the user to use TinyMCE to create content. The idea is to set the content, hit the "Get Data" button and have the modal disappear with the content from the editor now displaying inside the original div.
This is working as far as p utting the content in the div when I hit submit. The body of the modal disappears at this point, but the gray opacity screen that usually sits under the bootstrap modal is still present and I can't any longer do anything on the page. I'm wondering what I'm doing wrong here and how I can fix it to fully close the modal when I hit the submit button.
<div class="leftContent">
<div class="modal fade bd-example-modal-lg" id="leftFiftyModal" tabindex="-1" role="dialog" aria-labelledby="leftFiftyLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="leftFiftyModal">Content Library:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h3>Create your own content</h3>
<form id="form-data" method="post">
<textarea id="mytextarea"></textarea>
<input type="submit" value="Get Data">
</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">Save changes</button>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#form-data").submit(function(e){
var content = tinymce.get("mytextarea").getContent();
$(".leftContent").html(content);
return false;
});
jQuery.noConflict();
$('#leftFiftyModal').modal('hide');
});
</script>
Try:
<script type="text/javascript">
$(document).ready(function(){
$("#form-data").submit(function(e){
var content = tinymce.get("mytextarea").getContent();
$(".leftContent").html(content);
jQuery.noConflict();
$('#leftFiftyModal').modal('hide');
return false;
});
});
</script>

Change href of modal based on button click

Clicking this button opens the modal
<button type="button" id ="soldBtn" class="btn btn-info" data-toggle="modal" data-target="#myModal">This laptop has been sold</button>
This is the modal
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<p>Confirmation</p>
</div>
<div class="modal-body">
<p>Are you sure you want to do this?</p>
</div>
<div class="modal-footer">
<a class="btn btn-outline-success" id="confirmBtn" href="#" >Yes</a>
<a class="btn btn-outline-danger" id="cancelBtn" data-dismiss="modal">No</a>
</div>
</div>
</div>
</div>
</div>
I could just have a different modal for different buttons, but I'd rather follow the DRY principle. I'd like the href of the confirmBtn to change based on which button to open the modal was clicked. I've tried this so far but not even sure if I'm on the right track.
<script type="text/javascript">
if(jQuery('#soldBtn').data('clicked')) {
document.getElementById("confirmBtn").href="{%url 'laptops:sale'%}";
}
</script>
You should first wait for your DOM to load. This can be done by wrapping your script code with the following:
$(function(){
// Here you will place the code that follows
});
Then you should register an event handler for the click event on the DOM element with id soldBtn:
$("#soldBtn").on('click', function(){
var confirmBtnEle = $("#confirmBtn");
confirmBtnEle.attr('href','%url 'laptops:sale'%');
});
Apparently, you have to change the second argument we pass to attr method above to be that you want to be.

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.

Categories

Resources