FullCalendar and JQuery events - javascript

I made a Fullcalendar in my Laravel app. The render is exactly what I want : a calendar on the left and when users clic on a day, this day become "red", and the list of hours for meetings is create on the right.
See the result here (I have just blur the coach name ;) :
I create the list with this code in my calendar :
dateClick: function (info) {
//Colorize the select day in red
$('*').removeClass('activeday');
$('[data-date=' + info.dateStr + ']').addClass('activeday');
// Ajax for recover all events 'Disponible"
let qlq;
$.ajax({
url: 'events/get-disponibility',
method: 'GET',
dataType: 'json',
async: false,
data: {
date: info.dateStr,
},
error: function (request, status, error) {
console.log(request.responseText);
console.log(status);
console.log(error);
},
success: function (data) {
qlq = data;
}
});
let html = "<h3>Horaires et Coachs disponibles : </h3> <br>";
if (qlq.length) {
qlq.forEach(function (row) {
html = html + '<div class="container d-flex mb-3">\
<div class="col-6">\
<span id="puce">•</span>\
' + row.admin_prenom + ' ' + row.admin_nom + ' </div> \
<div class="col-6 justify-content-around">\
<span class="badge badge-pink">' + row.start_date.substring(11, 16) + '</span>\
<a href="#' + row.id + '" class="get-modal-event"\
data-idEvent=' + row.id + '>\
<span class="badge badge-dark">\
<i class="fas fa-arrow-right"></i>\
</span>\
</a>\
</div>\
</div>';
});
$("#freeCoach").empty()
.append(html);
} else {
$("#freeCoach").empty()
.append('<div class="container d-flex mb-3">\
<div class="col-12">\
<span id="puce">•</span>\
Pas de coach disponible à cette date. <br>\
<br>\
Seul les dates comportant un fond coloré comporte des disponibilités</div> \
</div>');
}
},
Now I just want to popup a bootstrap modal, when users click on the black arrow (a link whith the class "get-modal-event").
So I use, after my calendar render, this JQuery code :
$('a.get-modal-event').each(() => {
$(this).click(function (e) {
e.preventDefault();
alert('get modal !!!!!');
$('#modal-event').modal('show');
})
I have create an alert box to see that function work, but no alert is showing and no modal appears...
I tried to create a link outside of the calendar (with is own class for a test) and both alert and modal appear !
I also tried to put this code in a different file and build it, but the result is the same.
Any idea ?

The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound for dynamically created elements. you'll have to create a "delegated" binding by using [on()].
Here you'll need to use:
$('body').on('click', 'a.get-modal-event', function(e) {
e.preventDefault();
alert('get modal !!!!!');
$('#modal-event').modal('show');
});

Related

How to append big HTML snippets into DOM with Javascript?

I have an app which uses EJS templating to populate data.
In order to add new projects I have made a simple input form which takes all required parameters.
After an input completed an Ajax request being sent, on success I want to inject this snippet into DOM.
In simple words - After new project added I want to display play instantly by injecting into DOM without reloading the page
Is there an elegant way of inserting this div ladder as a template into DOM? It works,
<div class="projects">
<div class="projectHeader">
<div class="projectTitle">
<span>
<a data-toggle="modal" data-target="#editDeadLineModal">
<i data-id="<%=project.id%>" class="projectDeadline far fa-calendar-alt fa-2x" data-toggle="tooltip" data-placement="top" title="Set Deadline"></i>
</a>
</span>
<h5 class="projectName <%=project.id%>" data-toggle="tooltip" data-placement="top" title="Deadline <%=deadline%>" style="align-items: center;">
<%=project.name%>
</h5>
<%}%>
<div class="projectButtons">
<span data-toggle="tooltip" data-placement="top" title="Edit Project Title">
<a data-toggle="modal" data-target="#editProjectTitleModal">
<i id="editProjectName" class="editProject fas fa-pencil-alt" data-name="<%=project.name%>" data-id="<%=project.id%>"></i>
</a>
</span>
<i class="separatorDash fas fa-minus"></i>
<span data-toggle="tooltip" data-placement="top" title="Delete Project">
<a data-toggle="modal" data-target="#deleteProjectModal">
<i id="deleteProject>" class="deleteProject far fa-trash-alt" data-id="<%=project.id%>"></i>
</a>
</span>
</div>
</div>
</div>
</div>
What I have tried is recreating the entire div ladder in string and append it to parent node.
Like this:
// Add new Project
$('#addNewProjectBtn').on("click", function() {
$("#newProjectModal").on('show.bs.modal', function() {
$(".confirmNewList").on("click", function(event) {
var url = '/addNewList';
var newListTitle = $("#newListNameInput").val()
event.preventDefault();
$.post({
url: url,
data: {
listName: newListTitle
},
success: function(result) {
$("#newProjectModal").modal('hide')
$("#newListNameInput").val('');
var id = result.data.id
var name = result.data.name
//Append new project
$(".projects").append("<div class='project col-4' id='project" + id + "'> <div class='projectHeader'> <div class='projectTitle'> ...and so on until the end")
},
error: function(err) {
console.log(err);
}
})
}
}
})
})
})
In simple words - After new project added I want to display play instantly by injecting into DOM without reloading the page
Is there an more elegant and specially efficient way of inserting this div ladder as a template into DOM?
The method which I have tried above - works, But on attempt to interact with it by calling modals - modals do not get it's data-*, as well the bootstrap tooltips don't work.
you can try create new html file instead, and append like this in your page
$.get("yourfile.html", function (data) {
$("#appendToThis").append(data); // or use .html();
});
OR you can directly pass this HTML structure from your backend, so you can directly use append function.
After some research I discovered that the event handler can be delegated.
Since the html snippet I am trying to append to projects is added after document.ready (document is loaded and handlers are bind) the only thing required to make the new snippet be active on event is to delegate the event handler to the parent of element that is appended.
Like this :
$("body").delegate("#addNewProjectBtn", "click", function() {
$("#newProjectModal").on('show.bs.modal', function() {
$(".confirmNewList").on("click", function(event) {
var url = '/addNewList';
var newListTitle = $("#newListNameInput").val()
event.preventDefault();
$.post({
url: url,
data: {
listName: newListTitle
},
success: function(result) {
$("#newProjectModal").modal('hide')
$("#newListNameInput").val('');
var id = result.data.id
var name = result.data.name
//Append new project
$(".projects").append("<div class='project col-4' id='project" + id + "'> <div class='projectHeader'> <div class='projectTitle'> ...and so on until the end")
},
error: function(err) {
console.log(err);
}
})
}
}
})
})
})
By delegating the event handler to it's parent - the event handler is preserved in the parent.

onclick events don't work for ajax appended html using classic asp with Prestashop static html files [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I have been assigned to update a classic asp website with a Prestashop template called Autotune Responsive Prestashop Theme. My client wants all the ajax bells and whistles they see online in Template Monster. Template Monster made static html files for my client from this template which includes all the custom Prestashop javascript libraries. So far I am unable to use these custom Prestashop jquery/ajax libaries as they were intended so I have to write my own code to paginate, add to cart, show item popup, etc. Everything works great except for appending html. For example, pagination. When I view a list of parts in grid view and I click to append nine more parts, the html gets appended OK but onclick events to the Add To Cart button and "eye" icon popup are dead for the new items that were appended. Mouse over events are OK. Same issue when I append html to the cart popup - I see the added cart items in the cart popup but the "x" (delete) won't work when clicked although the color changes when moused over. It's as if I need to update something after appending. I'm stumped. Here is the pagination code:
$(function() {
$('#infiniteScrollMore').click(function(){
var numItems = parseInt($('#NumItems').text());
var pageNbr = parseInt($('#PageNbr').text()) + 1;
$('#PageNbr').text(pageNbr);
$.get('AppendParts.asp?PageNbr=' + pageNbr + '&NumItems=' + numItems,function (data) {
$('.product_list').append(data);
numNextItems = parseInt(numItems) - (parseInt(pageNbr) * 9);
if (parseInt(numNextItems) >= 9) numNextItems = 9;
setTimeout(function(){$('#NumNextItems').text(' (' + numNextItems + ')')},2000);
if ((parseInt(pageNbr) * 9) >= parseInt(numItems))
{
$('#infiniteScrollMore').hide();
setTimeout(function(){$('#NewSearchButton').show();},2000);
}
});
});
});
I am just using .append to append html to the product_list ul. AppendParts.asp writes the html, which is...
<li class="ajax_block_product">
<div class="product-container" itemscope itemtype="https://schema.org/Product">
<div class="left-block">
<div class="product-image-container">
<div class="tmproductlistgallery rollover">
<div class="tmproductlistgallery-images opacity">
<a class="product_img_link cover-image" href="product.asp?PartNbr=<%=pageCache("PartNbr")%>&StockNbr=<%=pageCache("StockNbr")%>&ProductCode=<%=pageCache("ProductCode")%>&MachineType=<%=pageCache("MachineType")%>&Model=<%=pageCache("Model")%>&Category=<%=pageCache("Category")%>&SubCategory=<%=pageCache("SubCategory")%>" title="<%=pageCache("Description") & " " & pageCache("Make") & " " & pageCache("PartNbr") & " " & pageCache("Class")%>" itemprop="url">
<img class="img-responsive" src="http://<%=theImage%>" alt="" title="<%=pageCache("Description") & " " & pageCache("Make") & " " & pageCache("PartNbr") & " " & pageCache("Class")%>">
</a>
<a class="product_img_link rollover-hover" href="product.asp?PartNbr=<%=pageCache("PartNbr")%>&StockNbr=<%=pageCache("StockNbr")%>&ProductCode=<%=pageCache("ProductCode")%>&MachineType=<%=pageCache("MachineType")%>&Model=<%=pageCache("Model")&Category=<%=pageCache("Category")%>&SubCategory=<%=pageCache("SubCategory")" title="<%=pageCache("Description") & " " & pageCache("Make") & " " & pageCache("PartNbr") & " " & pageCache("Class")%>" itemprop="url">
<img class="img-responsive" src="http://<%=theImage%>" alt="" title="<%=pageCache("Description") & " " & pageCache("Make") & " " & pageCache("PartNbr") & " " & pageCache("Class")%>">
</a>
</div>
</div>
<div class="functional-buttons">
<div class="qv-wrap">
<a class="quick-view" data-id="<%=pageCache("ProductCode") & ":" & pageCache("StockNbr") & ":" & pageCache("PartNbr")%>" href="#" onclick="return false;" data-fancybox-type="ajax" data-type="ajax" data-href="#" title="Quick View"></a>
</div>
<div class="compare">
<a class="add_to_compare" href="product.asp?PartNbr=<%=pageCache("PartNbr")%>&StockNbr=<%=pageCache("StockNbr")%>&ProductCode=<%=pageCache("ProductCode")%>&MachineType=<%=pageCache("MachineType")%>&Model=<%=pageCache("Model")%>&Category=<%=pageCache("Category")%>&SubCategory=<%=pageCache("SubCategory")%>" data-id-product="<%=pageCache("ProductCode") & ":" & pageCache("StockNbr") & ":" & pageCache("PartNbr")%>" title="Detailed View"></a>
</div>
</div>
... abbreviated a bit. Here is the fancybox code:
$(function() {
$('.quick-view').click(function(){
var idStrArray = $(this).attr('data-id');
var idStr = idStrArray.split(':');
var productCode = idStr[0];
var stockNbr = idStr[1];
var partNbr = idStr[2];
$.fancybox({
'closeClick': true,
'hideOnContentClick': true,
'padding': 0,
'width': 1021,
'autoDimensions': false,
'height': 500,
'type': 'iframe',
'tpl': {wrap: '<div class="fancybox-wrap fancybox-quick-view" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>'},
'href': 'product-popup.asp?PartNbr=' + partNbr + '&ProductCode=' + productCode + '&StockNbr=' + stockNbr,
'beforeClose': function() {}
}
});
});
});
What am I missing?
You have to the event trigger like this -
$( "body" ).on( "click", "p", function() {
alert( $( this ).text() );
});
Use jQuery .on() method. Read the doc

add class active only to the clicked category

I have a menu with some post categories:
<ul>
#foreach($categories->get() as $category)
<li class="ative">
{{$category->name}}
</li>
#endforeach
</ul>
When I click in the category, for example with id "1", through the menu it appears in the #posts div the posts that belong to the category with id "1".
Issue:
It working fine, the issue is that at first I want to have the first category with the class "active". But when another category is clicked I want to show that clicked category with the class active. But is not working like that, when the page is acessed all categories are active and also when another category is clicked all categories are active. Do you know how to correct the issue?
The #posts div shows the last posts when the page is acessed at first:
<div id="posts">
#foreach($posts as $key => $post)
<div id="post" + {{$key}}>
<img src="{{$post->image}}">
<h1>{{$post->title}}</h1>
<!-- ... -->
</div>
#endforeach
</div>
jQuery code:
$("a[name='category']").on('click', function(){
//tried this by given answer which not worked
var category_id = $(this).attr("id");
('.categories li').removeClass('active');
$(this).addClass('active');
//ended code
$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
var newPosts = "";
$.each(result, function(index, post) {
newPosts += '<img src="' + post.image + '">' + + '<h1>' + post.title + '</h1>';
});
$('#posts').html(newPosts);
}, error: function(error) {
console.log(error.status)
}
});
});
You need to add two line jquery code inside click event handler
$('ul li').removeClass('active');// remove active class from li
$(this).parent('li').addClass('active'); // add active class to current clicked li

Spring Boot Ajax populate a select options dynamically

Hello every one i have the following question ,i have a select tag that i want to populate with a list objects Here some code to explain:
#RequestMapping(value="/getAllIndustries")
#ResponseBody
public List<IndustryModel>getAllIndustries()
{
return generalSettingMerchantLookUpService.getBusinessNature(Constant.MERCHANT);
}
This return a list of industries models ,the following is the java script that i am using
function industryAjax()
{
alert("i am here")
var businessNatureId= $("#industrySelect option:selected").val();
$.ajax({
url : getContextPath() + "/getAllIndustries",
type : "get",
success : function(response) {
$('#industrySelect').empty();
$('#industrySelect').append($('<option>', {
value: 0,
text: 'Select'
}));
for (item in response) {
$('#industrySelect').append($('<option>', {
value: response[item].industryId,
text: response[item].industryInEnglish
}));
}
},
error : function(e) {
// alert("Submit failed" + JSON.stringify(e));
}
});
}
And here i my html
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
<label>Industry</label> <select class="form-control m-b"
id="industrySelect" name="industryId" onchange="industryChange();">
<option value="0">Choose Industry</option></select>
<p id="chooseIndustry" style="color: red;">please choose a valid industry</p>
</div>
So how can i display the list of industries that i get from controller in the html ,Best Regards
It might be the case that this method is not getting invoked because initially your dropdown does not contain any element. So there will not be any onchange event fired.
Try using below implementation:
$(document).on('click', "#industrySelect", function(event) {
industryAjax();
});

Fancybox will not use content passed via javascript

Using jquery 1.10.2, fancybox 2.1.5
I'm trying to pass fancybox the "content: data" via javascript but its not working. Yet if I console.log the data variable it shows me valid HTML/text, but fancybox refuses to use it.
<div class="item">
<h4 class="choice">launch modal</h4>
<div class="detail">
This should show up in my <b>fancybox</b>!
</div><!--.detail-->
</div><!--.item-->
$('.choice').each(function(i, elem){
$(elem).siblings('.detail').wrap('<div style="display:none"></div>');
});
$(".choice").fancybox({
maxWidth: 800,
content: 'replace this text',
beforeShow: function(){
var title = $(this.element).text();
var data = $(this.element).parent().find('.detail').html();
console.log('this=' + this + ' | title=' + title + ' | data=' + data);//DEBUG
this.content = data;
}
});
The console log shows clearly that its got the data html content, but fancybox refuses to use it. I've wrapped it in another div with display:none since their site says to do that for whatever reason.
To build your content inside the callback, use afterLoad instead, otherwise the content option will have preference over this.content within any other callback :
$(".choice").fancybox({
maxWidth: 800,
content: 'replace this text',
afterLoad: function () {
var title = $(this.element).text();
var data = $(this.element).parent().find('.detail').html();
console.log('this=' + this + ' | title=' + title + ' | data=' + data); //DEBUG
this.content = data;
}
});
See JSFIDDLE
Note: you can also build/replace the title as in your code above like this.title = title;

Categories

Resources