CKEditor is not working with bootstrap modal - javascript

I want to show ckEditor on bootstrap modal but the ckEditor is not opening as shown below. After searching through the internet I have got some solution in a different way like this link but I will perform an ajax request hence I have to open the modal using $('.cia_modal').modal('toggle'). The above-mentioned solution link does not work for me
Modal Button:
<button class="btn btn-info btn-xs cia_modal_btn" data-id="<?php echo $post->post_id; ?>" data-table="post" data-attr="post_id">
Create New Post
</button>
Modal:
<!--Modal-->
<div class="modal fade cia_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">Create New Post</h4>
</div>
<div class="modal-body">
<form action="/action_page.php">
<div class="form-group">
<textarea class="ck_editor" name="post" id="" cols="30" rows="10"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--End Modal-->
Javascript:
<script type="text/javascript">
$(document).on("click", ".modal_btn", function (e) {
e.preventDefault();
e.stopPropagation();
let cia_modal = $('.cia_modal');
//Set modal show/hide
cia_modal.modal('toggle');
let id = $(this).attr('data-id');
let table = $(this).attr('data-table');
let attr = $(this).attr('data-attr');
//Set Form Data
let formData = new FormData();
formData.append('id',id);
formData.append('table',table);
formData.append('attr',attr);
$.ajax({
type: 'post',
url: '<?php echo base_url()?>post/create_post',
data: formData,
contentType: false,
processData: false,
success: function (data) {
//
}
});
});
</script>
Please help me. Thanks

I assume, you are using CKEditor 4.x.
You need to create editor using CKEDITOR.replace( 'ck_editor' ), you can do it only on element that is existing inside document. It doesn't matter if it's hidden or not. If your modal is inside DOM, but hidden, then just initialize editor. Otherwise you need to wait until element is appended then call CKEDITOR.replace.
Depending on how bootstraps implements modal.show. If it's just changes CSS to make it visible, then most likely you can initialize editor at the start of your script, if it adds elements to document, then you need to use some of bootstrap events to create editor in right time. See shown.bs.modal: https://getbootstrap.com/docs/4.0/components/modal/#events

Just initialize the editor:
<script type="text/javascript">
ClassicEditor.create($('.ck_editor')[0])
.then( editor => {
console.log( editor );
})
.catch( error => {
console.log( error );
});
$(document).on("click", ".modal_btn", function (e) {
//....

Related

AJAX call not triggered on show.bs.modal

I have a button which is supposed to trigger a modal with a contact form. Part of the show.bs.modal function is an AJAX call to my DB to get some file details which are then meant to be shown in the modal-body.
The problem is that the modal does indeed open, but with no modal-body content, which means that the JavaScript code to trigger to the AJAX call is not working. I do not see any network activity in the browser debug menu, no call to the PHP file, and even an alert on top of the JS code telling me that that a button was pressed is not triggered. It seems like the whole JS code is circumvented, yet the modal still shows.
The same code works in another project, anyone has any idea as to why this is happening?
Button:
<div class="card-footer bg-light text-center">
<button id="modal_btn" name="modal_btn" type="button" class="btn bg-teal-400" data-toggle="modal" data-target="#modal_contact_form" data-imgid="'.$row['image_id'].'" data-keyboard="true">
<span class="icon-ico-mail4"></span> Anfragen
</button>
</div>
Modal:
<!-- Contact form modal -->
<div id="modal_contact_form" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-teal-300">
<h3 class="modal-title">Kaufanfrage - Artikel #1234</h3>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Abbrechen</button>
<button type="submit" class="btn bg-teal-300">Nachricht Senden</button>
</div>
</form>
</div>
</div>
</div>
<!-- /contact form modal -->
JavaScript:
<script type="text/javascript">
// DISPLAY EDIT RECORD MODAL
$('#modal_contact_form').on('show.bs.modal', function (event) {
//var button = $(event.relatedTarget) // Button that triggered the modal
window.alert("button clicked.");
var imgid = $(event.relatedTarget).data('imgid') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'action=contact&imgid=' + imgid;
$.ajax({
type: "POST",
url: "./assets/ajax/ajax_action.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
},
error: function(err) {
console.log(err);
}
});
});
</script>
try this:
$(document).on('show.bs.modal','#modal_contact_form', function (event) {
// TODO ....
});
Or you can use the onclick button trigger instead of modal show trigger
$("#modal_btn").click(function(event){
// TODO ...
});
Try This
const bsModal = document.querySelector('#exampleModal');
$(bsModal).on('shown.bs.modal', function() {
// YOUR CODE HERE....
})

modal show not working after modal(hide) in jquery after submit

I have table in modal with edit button to update the user details
<div class="modal fade" id="editModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">User Info</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form>
<div class="modal-body edit-info" >
</div>
<div class="modal-footer">
<button type="submit" class="roomupdate btn btn-warning">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
and my ajax code is
$(document).on('click', '.roomupdate', function(){
ev.preventDefault();
$id= $('#id').val();
$building=$('#building').val();
$floorno=$('#floorno').val();
$roomno=$('#roomno').val();
$priority=$('#priority1').val();
$nobeds=$('#nobeds').val();
$('#editModal').modal('hide');
$.ajax({
type: "POST",
url: "addroomlist.php",
async: false,
data: {
building: $building,
id: $id,
floorno: $floorno,
roomno: $roomno,
priority: $priority,
nobeds: $nobeds,
roomupdate: 1,
},
success: function(){
showUser();
},
});
});
and my edit button code to call modal with user info.
<td> <button data-id='<?php echo $row['id'] ?>' class='roomedit btn btn-warning'>Edit</button></td>
when i first click save button after modify the details its working fine and modal closed with
$('#editModal').Modal('hide');
when i click edit button second time Modal not show up until i reload the page.
where it went wrong please help
In your ajax code remove $('#editModal').modal('hide'); from the line where you are using right now and put it in success function of ajax.
Like:
success: function(){
$('#editModal').modal('hide');
showUser();},
and if you are using location.reload(); in your showUser(); function then it will work but as far i know i think you did not add it in showUser(); so add also location.reload(); after showUser(); function or at the end of code written in showUser(); function.
And one more thing do you write any code by which clicking on edit button the modal should open in javascript?

Uncaught RangeError: Maximum call stack size exceeded and [Violation] 'click' handler took

I checked other post like this but honestly I don't find a solution. I have a button "test", and when I hit the button theoretically I gotta open up a new window showing a query result but, I'm getting this error and honestly I'm not understanding why!
In item_action.php I wrote this code just for test:
if ($_POST['btn_action'] == 'item_view') { //View Item details
echo "test";
}
Below the code in the javascript file
//OPEN DETAIL ITEM WINDOW IN MODE VIEW
$('#test').on('click', function() {
//var item_id = $(this).attr("id");
//Declare 2 vars
var item_id = 3;
var btn_action = 'item_view';
$('#productModalView').modal('show');
$.ajax({
url: "item_action.php",
method: "POST",
data: {
product_id: product_id,
btn_action: btn_action
},
success: function(critto) {
$('#itemview').html(critto);
},
error: function() {
$('<div>').html('Found an error!');
}
});
});
<div id="productModalView" class="modal fade">
<div class="modal-dialog">
<form method="post" id="product_form_view">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><i class="fa fa-plus"></i>Item Product</h4>
</div>
<!-- Close Modal Header -->
<div class="modal-body">
<div id="itemview"></div>
</div>
<!-- Close Modal Body-->
<div class="modal-footer">
<input type="hidden" name="product_id" id="product_id" />
<input type="hidden" name="btn_action" id="btn_action" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<!-- Close Modal Footer -->
</div>
<!-- Close Modal Content -->
</form>
<!-- Close Form -->
</div>
<!-- Close Modal-Dialog -->
</div>
<!-- Close Product Modal -->
Any idea how to fix it???

Converting Bootstrap 3 remote modal to Bootstrap 4 modal with parameters

So in the near future my shop is going to upgrade to Bootstrap 4 but we cannot do this until we solve the issue with using remote modals. Here is an example of how we load our modals. The reason we use remote modals is because the modal-body is dynamic and may use different file based on the url. I have heard that using jQuery("#newsModal").on("load",..) is an alternative but how could I do this? I found this but I am not sure how my anchor would look and how to build the url to load the remote data.
Global PHP include file:
<div id="NewsModal" class="modal fade" tabindex="-1" role="dialog" data-
ajaxload="true" aria-labelledby="newsLabel" 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>
<h3 class="newsLabel"></h3>
</div>
<div class="noscroll-modal-body">
<div class="loading">
<span class="caption">Loading...</span>
<img src="/images/loading.gif" alt="loading">
</div>
</div>
<div class="modal-footer caption">
<button class="btn btn-right default modal-close" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
modal_news.php file:
<form id="newsForm">
<div id="hth_err_msg" class="alert alert-danger display-hide col-lg-12 col-md-12 col-sm-12 col-xs-12">
You have some errors. Please check below.
</div>
<div id="hth_ok_msg" class="alert alert-success display-hide col-lg-12 col-md-12 col-sm-12 col-xs-12">
✔ Ready
</div>
<!-- details //-->
</form>
Here is how we trigger the modals :
<a href="#newsModal" id="modal_sbmt" data-toggle="modal" data-target="#newsModal"
onclick="remote='modal_news.php?USER=yardpenalty&PKEY=54&FUNCTION=*GENERAL'; remote_target='#NewsModal .noscroll-modal-body'">
<span class="label label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
Promotional Ordering
</a>
I think I need to do something like this when building anchor dynamically:
a) Replace paramters with data-attrs
b) Use the event invoker to get the data-attrs using event.target.id
Thanks to Tieson T. and this post I was able to effectively pass parameters to the remote modal using this technique except if you have multiple modals
I have also included some helpful techniques inside this example as to how you may pass parameters to the remote modal.
bootstrap_modal4.php:
<div class="portlet-body">
Add Attendee <i class="fa fa-plus"></i>
</div>
<!-- BEGIN Food Show Attendee Add/Edit/Delete Modal -->
<div id="attendee" class="modal fade" tabindex="-1" role="dialog" data-ajaxload="true" aria-labelledby="atnLabel" aria-hidden="true">
<form id="signupForm" method="post">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<label id="atnLabel" class="h3"></label><br>
<label id="evtLabel" class="h6"></label>
</div>
<div class="modal-body">
<div class="loading"><span class="caption">Loading...</span><img src="/images/loading.gif" alt="loading"></div>
</div>
<div class="modal-footer">
<span class="caption">
<button type="button" id="add_btn" class="btn btn-success add-attendee hidden">Add Attendee <i class="fa fa-plus"></i></button>
<button type="button" id="edit_btn" class="btn btn-info edit-attendee hidden">Update Attendee <i class="fa fa-save"></i></button>
<button type="button" id="del_btn" class="btn btn-danger edit-attendee hidden">Delete Attendee <i class="fa fa-minus"></i></button>
<button class="btn default modal-close" data-dismiss="modal" aria-hidden="true">Cancel</button>
</span>
</div>
</div>
</div>
</form>
</div>
<script>
jQuery(document).ready(function() {
EventHandlers();
});
function EventHandlers(){
$('#attendee').on('show.bs.modal', function (e) {
e.stopImmediatePropagation();
if($(this).attr('id') === "attendee"){
// Determines modal's data display based on its data-attr
var $invoker = $(e.relatedTarget);
var fscode = $invoker.attr('data-fscode');
console.log(fscode);
// Add Attendee
if($invoker.attr('data-atnid') === "add"){
$("#atnLabel").text("Add New Attendee");
$(".add-attendee").removeClass("hidden");
}
else{ //edit/delete attendee
$("#atnLabel").text("Attendee Maintenance");
$(".edit-attendee").removeClass("hidden");
}
//insert hidden inputs
//add input values for post
var hiddenInput = '<INPUT TYPE=HIDDEN NAME=FSCODE VALUE="' + fscode + '"/>';
$("#signupForm").append(hiddenInput);
}
});
$('#attendee').on('hidden.bs.modal', function (e) {
$(".edit-attendee").addClass("hidden");
$(".add-attendee").addClass("hidden");
$("#signupForm input[type='hidden']").remove();
});
// BOOTSTRAP 4 REMOTE MODAL ALTERNATIVE FOR BOOTSTRAP 3v-
$('#add-attendee').on('click', function(e){
$($(this).data("target")+' .modal-body').load($(this).data("remote"));
$("#attendee").modal('show');
});
}
</script>
bootstrap_remote_modal4.php:
<form id="signupForm">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
Hello World!
</div>
</form>
<script>
$(document).ready(function(){
console.log('<?php echo $_GET["USERNAME"]?>'); //passed through url
});
</script>
NOTE: I am having problems with event propagation during the show.bs.modal event which I have a global show.bs.modal that is propagating up to this event handler due to multiple modals so if you have multiple modals make sure to handle them correctly.
Here is a screen shot of the results which clearly show propagation is taking place but the parameter passing techniques are working.
You might find it easier to use something like Bootbox.js, which can be used to dynamically create Bootstrap modals.
Given what you've shown, it would work something like:
trigger modal
with
$(function(){
$('.show-modal').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.get(url)
.done(function(response, status, jqxhr) {
bootbox.dialog({
title: 'Your Title Here',
message: response
});
});
});
});
This assumes response is an HTML fragment.
Bootbox hasn't officially been confirmed to work with Bootstrap 4, but I haven't run into any problems with it yet (modals seem to be one of the few components that don't have updated markup in BS4).
Disclaimer: I am currently a contributor to Bootbox (mainly updating the documentation and triaging issues).
If you must use only the Bootstrap modal, you're actually after load(). You would probably do something like:
$(function(){
$('.show-modal').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
var dialog = $('#NewsModal').clone();
dialog.load(url, function(){
dialog.modal('show');
});
});
});

Using Bootstrap Modal window as PartialView

I was looking to using the Twitter Bootstrap Modal windows as a partial view. However, I do not really think that it was designed to be used in this fashion; it seems like it was meant to be used in a fairly static fashion. Nevertheless, I think it'd be cool to be able to use it as a partial view.
So for example, let's say I have a list of Games. Upon clicking on a link for a given game, I'd like to request data from the server and then display information about that game in a modal window "over the top of" the present page.
I've done a little bit of research and found this post which is similar but not quite the same.
Has anyone tried this with success or failure? Anyone have something on jsFiddle or some source they'd be willing to share?
Thanks for your help.
Yes we have done this.
In your Index.cshtml you'll have something like..
<div id='gameModal' class='modal hide fade in' data-url='#Url.Action("GetGameListing")'>
<div id='gameContainer'>
</div>
</div>
<button id='showGame'>Show Game Listing</button>
Then in JS for the same page (inlined or in a separate file you'll have something like this..
$(document).ready(function() {
$('#showGame').click(function() {
var url = $('#gameModal').data('url');
$.get(url, function(data) {
$('#gameContainer').html(data);
$('#gameModal').modal('show');
});
});
});
With a method on your controller that looks like this..
[HttpGet]
public ActionResult GetGameListing()
{
var model = // do whatever you need to get your model
return PartialView(model);
}
You will of course need a view called GetGameListing.cshtml inside of your Views folder..
I do this with mustache.js and templates (you could use any JavaScript templating library).
In my view, I have something like this:
<script type="text/x-mustache-template" id="modalTemplate">
<%Html.RenderPartial("Modal");%>
</script>
...which lets me keep my templates in a partial view called Modal.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>{{Name}}</h3>
</div>
<div class="modal-body">
<table class="table table-striped table-condensed">
<tbody>
<tr><td>ID</td><td>{{Id}}</td></tr>
<tr><td>Name</td><td>{{Name}}</td></tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
</div>
</div>
I create placeholders for each modal in my view:
<%foreach (var item in Model) {%>
<div data-id="<%=Html.Encode(item.Id)%>"
id="modelModal<%=Html.Encode(item.Id)%>"
class="modal hide fade">
</div>
<%}%>
...and make ajax calls with jQuery:
<script type="text/javascript">
var modalTemplate = $("#modalTemplate").html()
$(".modal[data-id]").each(function() {
var $this = $(this)
var id = $this.attr("data-id")
$this.on("show", function() {
if ($this.html()) return
$.ajax({
type: "POST",
url: "<%=Url.Action("SomeAction")%>",
data: { id: id },
success: function(data) {
$this.append(Mustache.to_html(modalTemplate, data))
}
})
})
})
</script>
Then, you just need a trigger somewhere:
<%foreach (var item in Model) {%>
<a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
<%=Html.Encode(item.DutModel.Name)%>
</a>
<%}%>
I have achieved this by using one nice example i have found here.
I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.
Complete and clear example project
http://www.codeproject.com/Articles/786085/ASP-NET-MVC-List-Editor-with-Bootstrap-Modals
It displays create, edit and delete entity operation modals with bootstrap and also includes code to handle result returned from those entity operations (c#, JSON, javascript)
I use AJAX to do this. You have your partial with your typical twitter modal template html:
<div class="container">
<!-- Modal -->
<div class="modal fade" id="LocationNumberModal" 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">
Serial Numbers
</h4>
</div>
<div class="modal-body">
<span id="test"></span>
<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>
</div>
Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..
And the JSON Method in Controller:
public JsonResult LocationNumberModal(string partNumber = "")
{
//Business Layer/DAL to get information
return Json(new {
LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
},
JsonRequestBehavior.AllowGet
);
}
And then, in the view using your modal: You can package the AJAX in your partial and call #{Html.RenderPartial... Or you can have a placeholder with a div:
<div id="LocationNumberModalContainer"></div>
then your ajax:
function LocationNumberModal() {
var partNumber = "1234";
var src = '#Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
+ '?partNumber='' + partNumber;
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#LocationNumberModalContainer").html(data.LocationModal);
$('#LocationNumberModal').modal('show');
}
});
};
Then the button to your modal:
<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>
Put the modal and javascript into the partial view. Then call the partial view in your page.
This will handle form submission too.
Partial View
<div id="confirmDialog" class="modal fade" data-backdrop="false">
<div class="modal-dialog" data-backdrop="false">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Missing Service Order</h4>
</div>
<div class="modal-body">
<p>You have not entered a Service Order. Do you want to continue?</p>
</div>
<div class="modal-footer">
<input id="btnSubmit" type="submit" class="btn btn-primary"
value="Submit" href="javascript:"
onClick="document.getElementById('Coordinate').submit()" />
<button type="button" class="btn btn-default" data-
dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
Javascript
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#Coordinate").on('submit',
function (e) {
if ($("#ServiceOrder").val() == '') {
e.preventDefault();
$('#confirmDialog').modal('show');
}
});
});
</script>
Then just call your partial inside the form of your page.
Create.cshtml
#using (Html.BeginForm("Edit","Home",FormMethod.Post, new {id ="Coordinate"}))
{
//Form Code
#Html.Partial("ConfirmDialog")
}

Categories

Resources