Bootstrap modal not showing when click on pie chart slice - javascript

<script>
$(document).ready(function(){
//get the pie chart canvas
var cData = JSON.parse(`<?php echo $chart_data; ?>`);
var data = {
// labels: cData.label,
datasets: [{
label: "Users Count",
data: cData.data,
backgroundColor: [
"#FF0000",
"#FFFF00",
"#008000",
],
borderColor: [
"#FF0000",
"#FFFF00",
"#008000",
],
borderWidth: [1, 1, 1]
}]
};
var options = {
responsive: true,
title: {
display: true,
position: "top",
text: "All Subject Progress",
fontSize: 18,
fontColor: "#111"
},
legend: {
display: true,
position: "bottom"
// labels: {
// fontColor: "#333",
// fontSize: 16
// }
}
};
var canvas = document.getElementById("pie-chart");
var ctx = canvas.getContext("2d");
var myNewChart = new Chart(ctx, {
type: 'pie',
data: data
});
canvas.onclick = function(evt) {
var activePoints = myNewChart.getElementsAtEvent(evt);
if (activePoints[0]) {
var chartData = activePoints[0]['_chart'].config.data;
var idx = activePoints[0]['_index'];
var label = chartData.labels[idx];
var value = chartData.datasets[0].data[idx];
var url = "http://example.com/?label=" + label + "&value=" + value;
//console.log(url);
//alert(url);
$("#myChartmodal").modal("show");
}
};
});
</script>
<div id="myChartmodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
In this code I am creating pie-chart where it working perfectly. Now, I want to show bootstrap modal when I canvas.onclick. Here, What happen when I click on canvas.onclick only alert message are showing right now but $("#myChartmodal").modal("show"); is not working I don't know why. So, How can I open bootstrap modal after click on every slice of pie-chart? Please help me.
Thank You

Your show modal code should work as shown below, just need to include the bootstrap libraries as shown below
$(function(){
$('show').on('click', function(){
$('#myChartmodal').modal('show');
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<div id="myChartmodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<input type="button" value="Show Popup" id="show" data-toggle="modal" data-target="#myChartmodal">

Related

CropperJS Not working well when using it in modal

I am building a list of images that can be modified through a boostrap modal using Cropper js.
<% crop.forEach(function(crops) { %>
<div class="card mb-4 box-shadow" style="margin-right: 1em;">
<img data-enlargable class="card-img-top" src="/photos/cropped_images/<%= crops.cat_nom %>/<%= crops.nom %>"
alt="<%= crops.nom %>" style="max-height: 255px; max-width: 348px; object-fit: contain; cursor: zoom-in;">
<input type="hidden" id="dataImage" data-catname="<%= crops.cat_nom %>" data-idcrop="<%= crops.cropped_id %>">
<div class="card-body">
<h5 class="card-title"><%= crops.cat_nom %></h5>
<p class="card-text"><%= crops.nom %></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<button type="button" name="edit" class="btn btn-sm btn-outline-secondary"
data-path="/photos/cropped_images/<%= crops.cat_nom %>/<%= crops.nom %>"
data-target="#modal" data-toggle="modal">Edit</button>
</div>
</div>
</div>
</div>
<% }) %>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Cropper</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="img-container">
<img id="image" src="" alt="Picture" style="max-width: 100%">
<input type="hidden" id="dataGetter">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" id="editCropToDb">Save</button>
</div>
</div>
</div>
</div>
</div>
And here is the script i've come up with to get the img src and pass it to the image tag inside the modal so Cropper can use it.
I've also added some logic to upload it to my server.
$('button[name="edit"]').click(function (event) {
var src = $(this).parents('.card').find('img').attr('src')
var crop_id = $(this).parents('.card').find('input').data('idcrop')
var cat_name = $(this).parents('.card').find('input').data('catname')
$('#dataGetter').data('idcrop', crop_id)
$('#dataGetter').data('catname', cat_name)
$('#dataGetter').data('source', src)
var image = document.getElementById('image');
$('#image').attr('src', src)
})
window.addEventListener('DOMContentLoaded', function () {
var image = document.getElementById('image');
var cropBoxData;
var canvasData;
var cropper;
console.log(image)
$('#modal').on('shown.bs.modal', function () {
cropper = new Cropper(image, {
autoCropArea: 0.7,
viewMode: 1,
center: true,
dragMode: 'move',
movable: true,
scalable: true,
guides: true,
zoomOnWheel: true,
cropBoxMovable: true,
wheelZoomRatio: 0.1,
ready: function () {
//Should set crop box data first here
cropper.setCropBoxData(cropBoxData).setCanvasData(canvasData);
}
})
}).on('hidden.bs.modal', function () {
cropBoxData = cropper.getCropBoxData();
canvasData = cropper.getCanvasData();
cropper.destroy();
})
document.getElementById('editCropToDb').addEventListener('click', function () {
var initialUrl
var canvas
var crop_id = $('#dataGetter').data('idcrop')
var cat_name = $('#dataGetter').data('catname')
console.log(crop_id + '/' + cat_name)
if (cropper) { canvas = cropper.getCroppedCanvas() }
image.src = canvas.toDataURL();
canvas.toBlob(function (blob) {
var formData = new FormData()
formData.append('catname', cat_name)
formData.append('crop_id', crop_id)
formData.append('croppedImage', blob, 'croppedImage.png')
$.ajax('cropped/edit', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
alert('Modification faite')
location = '/cropped'
},
error: function () {
alert('erreur')
location = '/cropped'
}
})
})
})
});
The problem i'm getting is when i click the "edit" Button after the page is loaded, the modal shows up but Cropper doesn't start.
If i close it and open it again, Cropper starts properly and I can crop my image and upload it.
I'm just a beginner with jquery and all so maybe i can get any advice and help on this !
I figured it out ! I have been struggling to find a way to initialize the cropper after updating my
<img id="image ...> which was being tough.
What i ended up doing is destroying the cropper first and then initialize it again.
$('#modal').on('shown.bs.modal', function () {
$('#image').cropper('destroy')
cropper = new Cropper(image, {
autoCropArea: 0.7,
viewMode: 1,
center: true,
dragMode: 'move',
movable: true,
scalable: true,
guides: true,
zoomOnWheel: true,
cropBoxMovable: true,
wheelZoomRatio: 0.1,
ready: function () {
//Should set crop box data first here
cropper.setCropBoxData(cropBoxData).setCanvasData(canvasData);
}
})
Really was a dumb mistake from my part, but hoping this could help someone in the future !
You need to destroy() your initialized cropper right before reinitializing it. Don't do it in the function of closing your modal.

Quill Editor - unable to set data on click

I am using quill editor and inside the bootstrap modal and its work fine while inserting the data in data-* attribute in the form of JSON
So what's the problem :
The problem is when I tried to set the data in the quill editor using setContent api it does not work
/*
====================
Quill Editor
====================
*/
var quill = new Quill('#editor-container', {
modules: {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block']
]
},
placeholder: 'Compose an epic...',
theme: 'snow' // or 'bubble'
});
Here is my jsfiddle ( before using this read the instruction below )
How to use my fiddle:
Click on the add element button.
Type anything inside the quill editor
Hit the save change button.
Now you will see an element prepend dynamically using js
Inspect the Dynamic Element. You will see the data-text attribute with quill json data.
Now, Click on the Dynamic Element it opens the modal now the problem occurs it does not set the content value that it is fetching form data-* attribute.
The trick was converting the JSON string back into a JSON object:
From this: var dataText = $(this).attr('data-text');
To this: var dataText = JSON.parse($(this).attr('data-text'));
Updated Fiddle
var quill = new Quill('#editor-container', {
modules: {
toolbar: [
[{
header: [1, 2, false]
}],
['bold', 'italic', 'underline'],
['image', 'code-block']
]
},
placeholder: 'Compose an epic...',
theme: 'snow'
});
function modalclick() {
$(".dynamic-element").on('click', function(event) {
var dataText = JSON.parse($(this).attr('data-text'));
$('#exampleModalLong').modal('show');
quill.setContents(dataText);
console.log(dataText);
})
}
$("#addElement").on('click', function(event) {
var delta = quill.getContents();
var $_textDelta = JSON.stringify(delta);
console.log($_textDelta);
$html = "<div class='dynamic-element' data-text='" + $_textDelta + "'>" +
"<div>dynamic-element</div>" +
"</div>";
$(".element").prepend($html);
modalclick();
$('#exampleModalLong').modal('hide');
})
//modalclick();
$("#openmodal").on('click', function(event) {
$('#exampleModalLong').modal('show');
})
$('#exampleModalLong').on('hidden.bs.modal', function(e) {
quill.deleteText(0, 2000);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet"/>
<!-- Button trigger modal -->
<input type="button" id="openmodal" class="btn btn-info btn-rounded mb-4" value="Add element">
<div class="element">
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">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 id="editor-container">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" id="addElement" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>

jquery ajax post after close

I have data-id and I want to post data-id after my modal hide/close how can I do that ?
$(function() {
var popup = $('#AniPopup');
var time = $(".will-close strong");
var closeSeconds = $("#AniPopup").attr("data-close");
var openSeconds = $("#AniPopup").attr("data-open");
var dataSrc = $("#AniPopup").attr("data-src");
var dataId = $("#AniPopup").attr("data-id");
setTimeout(function(e) {
popup.modal('show');
time.html(closeSeconds);
setInterval(function(){
time.html(closeSeconds);
closeSeconds--;
if(closeSeconds < 0){
popup.modal('hide');
}
}, 1000)
}, openSeconds * 1000);
$.ajax({
url: dataSrc,
dataType: "html",
success: function(data) {
$(".modal-body").html(data);
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="modal fade" id="AniPopup" tabindex="-1" role="dialog" aria-labelledby="AniPopupLabel" aria-hidden="true" data-close="10" data-open="2" data-src="http://www.anitur.com.tr/popup/test-6-text" data-id="69">
<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="memberModalLabel">Popup Header</h4>
</div>
<div class="modal-body">
this content loaded by ajax
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Kapat</button>
<span class="will-close">will be closed after : <strong>n</strong> seconds</span>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Use standard event hidden.bs.modal of bootstrap modal:
$("#AniPopup").on('hidden.bs.modal', function () {
// do your staff here
});

How can I show Bootstrap modal when on click in individual bars in chart.js

I am working on a project using chart.js. I am trying to show a bootstrap modal when clicking individual bars instead of tooltip in chart js. Right now I am using chart id's onclick function for showing a bootstrap modal. Is there any way to make it possible.?
Here is my code:
HTML:
<div class="chart1">
<canvas id="barchart5"></canvas>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<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">
...
</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>
JAVASCRIPT :
<script type="text/javascript">
var data5 ={
labels: ["Label1", "Label2", "Label3", "Label4", "Label5", "Label6", "Label7", "Label8"],
datasets : [
{
fillColor : "#F64747",
strokeColor : "#F64747",
highlightFill: "#F64747",
highlightStroke: "#F64747",
data: [4, 6, 3, 2, 10, 5, 5, 7]
},
{
fillColor : "#19B5FE",
strokeColor : "#19B5FE",
highlightFill : "#19B5FE",
highlightStroke : "#19B5FE",
data: [3, 6, 4, 3, 10, 10, 5, 8]
},
{
fillColor : "#F7CA18",
strokeColor : "#F7CA18",
highlightFill : "#F7CA18",
highlightStroke : "#F7CA18",
data: [4, 6, 10, 4, 7, 6, 2, 4]
}
]
};
var ctx = document.getElementById("barchart5").getContext("2d");
var barchart5 = new Chart(ctx).Bar(data5, {
responsive : true,
showTooltips: false,
onAnimationComplete: function () {
var ctx = this.chart.ctx;
alert(ctx);
ctx.font = this.scale.font;
ctx.fillStyle = this.scale.textColor
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
this.datasets.forEach(function (dataset) {
dataset.bars.forEach(function (bar) {
ctx.fillText(bar.value, bar.x, bar.y);
});
})
}
});
$( "#barchart5" ).click(function() {
$('#myModal').modal('show');
});
</script>
canvas.onclick = function(evt) {
var points = chart.getBarsAtEvent(evt);
var value = chart.datasets[0].points.indexOf(points[0]);
if(value == 5){
$('#myModal').modal('show');
} else if(value == 4){
$('#myModal1').modal('show');
}
};
see this,
Click events on Pie Charts in Chart.js
don't know much about chart.js but I'm sure this library has some method to do this easily, no need to use jquery.

Bootstrap Modal and Badges

I have the following lines of code in my webpage - example/demo.
HTML:
<p data-toggle="modal" data-target="#messagesModal">Messages <span class="badge">2</span>
</p>
<!-- Modal -->
<div class="modal fade" id="messagesModal" 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>
<h4 class="modal-title">Messages</h4>
</div>
<div class="modal-body">
<div class="alert fade in">
×
<strong>Message 01</strong>:
<p>Lipsum Ipsum
</p>
</div>
<div class="alert fade in">
×
<strong>Message 02</strong>:
<p>Ipsum Lipsum</p>
</div>
</div>
<div class="modal-footer">
<div class="col-md-8 pull-left">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
How can I update the badge to represent the correct amount of messages in the modal?
For example, when the user closes or removes a message in the modal, the badge will go from displaying the number 2 to 1?
Also, is it possible to display the text "There are no more messages." when all of the messages have been removed?
Try this:
//Find message number initially, before editing
$(".badge").text($(".alert").length);
//when the modal is closed
$('#messagesModal').on('hidden.bs.modal', function () {
//Set .badge text equal to the length of the .alert array, i.e the number of messages
$(".badge").text($(".alert").length);
//If there are no '.alert' divs, i.e. no messages
if ($(".alert").length == 0) {
$(".badge").text("No messages");
}
});
This takes all the .alert elements (messages) into an array, and sees how long that array is (i.e. how many messages there are).
Then, it updates .badge to reflect that number.
Working JSFiddle: http://jsfiddle.net/joe_young/62hbqmtp/
Well... I've spend some time, but all that you should do for now:
populate message array with your actual data;
add some actual AJAX for removing messages.
So...
$(function() {
var informer = $("#messageInformer a");
var refreshBadge = function(messageCount) {
var badge = informer.find(".badge");
if (messageCount > 0) {
if (!badge.length) {
informer.text("Messages ");
informer.append("<span class=\"badge\">" + messageCount + "</span>");
} else {
badge.text(messageCount);
}
} else {
informer.text("No messages");
}
};
var buildMessage = function(message) {
var htmlMessage = "<div class=\"alert fade in\">";
htmlMessage += "×";
htmlMessage += "<strong>" + message.title + "</strong>:";
htmlMessage += "<p>" + message.text + "</p>";
return htmlMessage;
}
// There should be real data
var messages = [
{ id: "1", title: "Message 01", text: "Lipsum Ipsum" },
{ id: "2", title: "Message 02", text: "Ipsum Lipsum" }];
refreshBadge(messages.length);
informer.on("click", function(e) {
e.preventDefault();
var modalBody = $(".modal-body");
modalBody.empty();
for (var i = 0; i < messages.length; i++) {
modalBody.append(buildMessage(messages[i]));
}
});
$("body").delegate(".alert .close", "click", function() {
var messageId = $(this).data("id");
// There should be some AJAX possibly
messages = messages.filter(function(el) {
return el.id != messageId;
});
if (messages.length == 0) {
$("#messagesModal").modal("hide");
}
refreshBadge(messages.length);
});
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<p data-toggle="modal" data-target="#messagesModal" id="messageInformer">Messages <span class="badge"></span>
</p>
<!-- Modal -->
<div class="modal fade" id="messagesModal" 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>
<h4 class="modal-title">Messages</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<div class="col-md-8 pull-left">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>

Categories