Summernote dynamic contents in dropdown - javascript

I created dropdownnemu:
var format = function (context) {
var ui = $.summernote.ui;
// create button
var buttonGroup = ui.buttonGroup([
ui.button({
className: 'dropdown-toggle dropdown-format',
contents: 'Формат',
tooltip: 'Формат листа для печати',
container: false,
data: {
toggle: 'dropdown'
},
click: function() {
context.invoke('editor.saveRange');
}
}),
ui.dropdown({
className: 'dropdown-menu dropdown-formatlist',
contents:"<a class=\"dropdown-item\" >A5</a>",
callback: function ($dropdown) {
$dropdown.find('a').each(function () {
$(this).click(function(e) {
var format = $(this).text();
$(".dropdown-format").text(format);
e.preventDefault();
});
});
}
})
]);
return buttonGroup.render(); // return button as jquery object
};
Everything is okey.But if i adding dynamic content after ajax:
$.ajax({
....
success: function(data, textStatus, jqXHR) {
$('.dropdown-menu').prepend("<a class=\"dropdown-item\">"+data.data+"</a>")
});
dropdown-item inserted in html (.dropdown-menu),but when i click on this dropdown-item nothing happens. How add dynamic content on Summernote ?

Related

Bootstrap modal js is giving Synchronous XMLHttpRequest on the main thread is deprecated message

I am using Bootstrap Modal Js. However, whenever the modal pops up , I am getting this error
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
Also, in one page I am getting the erorr below when the modal launches using
if (auth=="False"){
setTimeout(function(){
if ($('#registerModal').hasClass('show')){
}else{
$('.register-btn').trigger('click');
}
}, 25000);
}
Error:
jquery.validate.unobtrusive.min.js:5 Uncaught TypeError: Cannot set property 'unobtrusive' of undefined
at jquery.validate.unobtrusive.min.js:5
at jquery.validate.unobtrusive.min.js:5
Here is the js
/*
django-bootstrap-modal-forms
version : 2.0.1
Copyright (c) 2020 Uros Trstenjak
https://github.com/trco/django-bootstrap-modal-forms
*/
(function ($) {
// Open modal & load the form at formURL to the modalContent element
var modalForm = function (settings) {
$(settings.modalID).find(settings.modalContent).load(settings.formURL, function () {
settings.asyncSettings=true;
settings.async = true;
$(settings.modalID).modal("show");
$(settings.modalForm).attr("action", settings.formURL);
addEventHandlers(settings);
});
};
var addEventHandlers = function (settings) {
// submitBtn click handler
$(settings.submitBtn).on("click", function (event) {
isFormValid(settings, submitForm);
});
// Modal close handler
$(settings.modalID).on("hidden.bs.modal", function (event) {
$(settings.modalForm).remove();
});
};
// Check if form.is_valid() & either show errors or submit it via callback
var isFormValid = function (settings, callback) {
$.ajax({
type: $(settings.modalForm).attr("method"),
url: $(settings.modalForm).attr("action"),
data: new FormData($(settings.modalForm)[0]),
contentType: false,
processData: false,
beforeSend: function () {
$(settings.submitBtn).prop("disabled", true);
},
success: function (response) {
if ($(response).find(settings.errorClass).length > 0) {
// Form is not valid, update it with errors
$(settings.modalID).find(settings.modalContent).html(response);
$(settings.modalForm).attr("action", settings.formURL);
// Reinstantiate handlers
addEventHandlers(settings);
} else {
// Form is valid, submit it
callback(settings);
}
}
});
};
// Submit form callback function
var submitForm = function (settings) {
if (!settings.asyncUpdate) {
$(settings.modalForm).submit();
} else {
var asyncSettingsValid = validateAsyncSettings(settings.asyncSettings);
var asyncSettings = settings.asyncSettings;
if (asyncSettingsValid) {
var formdata = new FormData($(settings.modalForm)[0]);
// Add asyncUpdate and check for it in save method of CreateUpdateAjaxMixin
formdata.append("asyncUpdate", "True");
$.ajax({
type: $(settings.modalForm).attr("method"),
url: $(settings.modalForm).attr("action"),
data: formdata,
contentType: false,
processData: false,
success: function (response) {
var body = $("body");
if (body.length === 0) {
console.error("django-bootstrap-modal-forms: <body> element missing in your html.");
}
body.prepend(asyncSettings.successMessage);
// Update page without refresh
$.ajax({
type: "GET",
url: asyncSettings.dataUrl,
dataType: "json",
success: function (response) {
// Update page
$(asyncSettings.dataElementId).html(response[asyncSettings.dataKey]);
// Add modalForm to trigger element after async page update
if (asyncSettings.addModalFormFunction) {
asyncSettings.addModalFormFunction();
}
if (asyncSettings.closeOnSubmit) {
$(settings.modalID).modal("hide");
} else {
// Reload form
$(settings.modalID).find(settings.modalContent).load(settings.formURL, function () {
$(settings.modalForm).attr("action", settings.formURL);
addEventHandlers(settings);
});
}
}
});
}
});
}
}
};
var validateAsyncSettings = function (settings) {
var missingSettings = [];
if (!settings.successMessage) {
missingSettings.push("successMessage");
console.error("django-bootstrap-modal-forms: 'successMessage' in asyncSettings is missing.");
}
if (!settings.dataUrl) {
missingSettings.push("dataUrl");
console.error("django-bootstrap-modal-forms: 'dataUrl' in asyncSettings is missing.");
}
if (!settings.dataElementId) {
missingSettings.push("dataElementId");
console.error("django-bootstrap-modal-forms: 'dataElementId' in asyncSettings is missing.");
}
if (!settings.dataKey) {
missingSettings.push("dataKey");
console.error("django-bootstrap-modal-forms: 'dataKey' in asyncSettings is missing.");
}
if (!settings.addModalFormFunction) {
missingSettings.push("addModalFormFunction");
console.error("django-bootstrap-modal-forms: 'addModalFormFunction' in asyncSettings is missing.");
}
if (missingSettings.length > 0) {
return false;
}
return true;
};
$.fn.modalForm = function (options) {
// Default settings
var defaults = {
modalID: "#modal",
modalContent: ".modal-content",
modalForm: ".modal-content form",
formURL: null,
errorClass: ".invalid",
submitBtn: ".submit-btn",
asyncUpdate: true,
asyncSettings: {
closeOnSubmit: false,
successMessage: null,
dataUrl: null,
dataElementId: null,
dataKey: null,
addModalFormFunction: null
}
};
// Extend default settings with provided options
var settings = $.extend(defaults, options);
this.each(function () {
// Add click event handler to the element with attached modalForm
$(this).click(function (event) {
// Instantiate new form in modal
modalForm(settings);
});
});
return this;
};
}(jQuery));

Reload DATATABLE inside AJAX success without refreshing page

I have a table using Datatable plugin. I have filtered what I want to delete and after deletion, I manage to empty the value.
After that, if I want to filter using the same text again, for example, I have ba 1 and ba 2 and after deleting ba 1, it still shows the cell when I entered ba on the filter textarea field. It suppose to display the remaining ba which are not deleted yet.
For your information, I'm not using built in Datatable Ajax method.
what I'm trying to do is I want it to reload the table with the new data without refreshing the page after ajax on success. How to do that?
My datatable :
var table1 = $('#table1').DataTable(
{
pageLength : 500,
lengthChange: false,
deferRender: true,
scrollY: 800,
scrollCollapse: true,
scrollX: true,
bSort: false,
cache: true,
autoWidth: false,
columnDefs: [
{
targets: 0,
checkboxes:
{
selectRow: true
}
}
],
select: {
style: 'multi',
selector: 'td:not(:nth-child(4), :nth-child(5), :nth-child(6), :nth-child(9), :nth-child(10), :nth-child(13), :nth-child(14), :nth-child(15), :nth-child(16), :nth-child(17), :nth-child(18), :nth-child(19), :nth-child(20), :nth-child(21), :nth-child(22), :nth-child(23), :nth-child(24), :nth-child(25))'
}
});
Here's my filtering function code :
table1.columns().every(function ()
{
var table = this;
$('.filter', this.header()).on('keyup change', delay(function (settings, data, dataIndex)
{
if (table.search() !== this.value)
{
table.search(this.value).draw();
}
}, 500));
});
Here's my AJAX success code for deletion based on selected checkbox:
$('.btnN2').click(function(){
var answer = confirm('Delete N2 : Are you sure you want to delete selected items?');
if (answer)
{
console.log('yes');
var rows = $(table1.rows({selected: true}).$('input[type="checkbox"]').map(function()
{
return $(this).prop("checked") ? $(this).closest('tr').attr('data-getstockcode') : null;
}));
var getstockcodes = [];
$.each(rows, function(index, rowId)
{
console.log(rowId)
getstockcodes.push(rowId);
});
$.ajax({
url: 'del_n2',
type: 'GET',
data: {"getstockcodes": JSON.stringify(getstockcodes)},
dataType: 'JSON',
success:function(data){
console.log(data);
$(table1.rows({selected: true}).$('input[type="checkbox"]').map(function()
{
if($(this).prop("checked"))
{
$(this).parents("tr:eq(0)").find(".note2").val('');
console.log('reset');
}
}));
}
});
}
else
{
console.log('cancel');
}
});
Here's my insert data based on keyup event
$(".note2").keyup(delay(function()
{
var stockcode = $(this).data("stockcode");
var stockname = $(this).data("stockname");
var value = $(this).val().replace(/(\r\n|\n)/g, "\\n");
$.ajax({
url: 'saveNote2',
type: 'GET',
data: 'stockcode='+stockcode+'&stockname='+stockname+'&value='+value,
dataType: 'JSON',
success: function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
}, 300));
Just add this in your success function
table1.ajax.reload()
If you are using ajax datatable or local you need to make it like this
table1.clear();
table1.rows.add(your response data array);
table1.draw()

Bootstrap Popover with Ajax call not showing data

I can't seem to update the popovers contents with Ajax result.
ASP.Net (MVC4):
public ActionResult GetEmployeeDetails(string employeeId)
{
var contract = UnitOfWork.ContractRepository.ContractBusinessManager.GetContract(int.Parse(employeeId), DateTime.Now);
return PartialView("_EmployeeDetails", contract);
}
Html:
<a data-toggle-popup-employee-id="#evaluation.EmployeeId" >#evaluation.Employee.FullName.ToTitle()</a>
Javascript:
$(document).ready(function () {
$('[data-toggle-popup-employee-id]').popover(
{
html: true,
placement: 'top',
title: 'Title',
container: 'body',
content: function () {
//$(this).off('hover');
var employeeId = $(this).data('toggle-popup-employee-id');
$.ajax({
async: false,
url: '#Url.Action("GetEmployeeDetails", "Evaluation")',
data: { employeeId: employeeId },
success: function (result) {
return result;
//var html = result;
//$(this).contents.html = result;
},
error: function (xhr) {
alert(xhr.responseText);
}
})
},
trigger: 'hover'
});
});
The call works fine and gives back the partial result as html but the popovers content is still empty...
UPDATE:
It appears that every time I hover over the link, 10 [Object, HTMLAnchorElement]
are added directly to the $('[data-toggle-popup-employee-id]').
Each object has InnerText and InnerHtml set to the employees name...?
I'd personally do something like the following...
$(document).ready(function () {
$('[data-toggle-popup-employee-id]').on({
mouseenter: function () {
var originator = $(this);
var employeeId = originator.data('toggle-popup-employee-id');
$.get('#Url.Action("GetEmployeeDetails", "Evaluation")', { employeeId: employeeId }, function (data) {
originator.popover({
html: true,
placement: 'top',
title: 'Title',
container: 'body',
content: data,
}).popover('show');
})
},
mouseleave: function () {
//
// Destroy so the data will referesh
//
$(this).popover('destroy');
}
});
});
This way we are initialising the popover in the callback of the ajax request.
Hope this makes sense.
$('.popover.in .popover-inner').html(data);

Jediitable, autocomplete and autogrow jquery not working

I am trying to use autocomplete and autogrow with the Jeditable jquery plugin and cannot seem to incorporate both. I currently have the Jeditable + autocomplete working perfectly. When I tr to add code for the autogrow it doesn't work and causes a post back when I hit the save button. Any help would be appreciated.
This is what I have so far:
$('#directionList').autocomplete({
source: function (request, response) {
$.ajax({
url: '../api/standarddirections/?q=' + request.term,
dataFilter: function (data) { return data; },
success: response
});
},
minLength: 2
});
$.editable.addInputType('autocomplete', {
element: $.editable.types.textarea.element,
plugin: function (settings, original) {
$('textarea', this).autocomplete(settings.autocomplete);
}
});
$(".directionAutoComplete").editable(function (value, settings) {
console.log(this);
console.log(value);
console.log(settings);
return (value);
}, {
type: "autocomplete",
indicator: 'Saving...',
tooltip: "Enter a direction...",
onblur: function (value, settings) {
console.log(this);
console.log(value);
console.log(settings);
return (value);
},
cancel: 'Cancel',
submit: 'Save',
autocomplete: {
source: function (request, response) {
$.ajax({
url: '../api/standarddirections/?q=' + request.term,
dataFilter: function (data) { return data; },
success: response
});
},
minLength: 2
}
});
Here's some reference material:
Jeditable
Jeditable - Auto Grow Tutorial
For those running into this problem I have gotten it to work. I went with the growfield plugin just because the autogrow one was having some weird results (it worked, but the formatting looked off when I saved it so I just opted to go the easier route of using a different plugin.)
Here's my final code:
$.editable.addInputType('growfield', {
element: function (settings, original) {
var textarea = $('<textarea>');
if (settings.rows) {
textarea.attr('rows', settings.rows);
} else {
textarea.height(settings.height);
}
if (settings.cols) {
textarea.attr('cols', settings.cols);
} else {
textarea.width(settings.width);
}
// will execute when textarea is rendered
textarea.ready(function () {
// implement your scroll pane code here
});
$(this).append(textarea);
return (textarea);
},
plugin: function (settings, original) {
// applies the growfield effect to the in-place edit field
$('textarea', this).growfield(settings.growfield);
$('textarea', this).autocomplete(settings.autocomplete);
}
});
$(".directionAutoComplete").editable(function (value, settings) {
console.log(this);
console.log(value);
console.log(settings);
return (value);
}, {
type: "growfield",
indicator: 'Saving...',
tooltip: "Enter a direction...",
onblur: function (value, settings) {
console.log(this);
console.log(value);
console.log(settings);
return (value);
},
cancel: 'Cancel',
submit: 'Save',
growfield: {},
autocomplete: {
source: function (request, response) {
$.ajax({
url: '../api/standarddirections/?q=' + request.term,
dataFilter: function (data) { return data; },
success: response
});
},
minLength: 2
}
});

jQuery Autocomplete can't replace only part of input value

I am trying to make autocomplete like on Github.
We have a textarea where we write in it some text. We also put -> '#' and try to auto complete a username.
When we the autocomplete script runs it removes all of the text.
My script:
function getSign(text){
var indexOfAt = text.lastIndexOf('#');
return indexOfAt;
};
function changeText(event, ui) {
var selectedElement = event.target.innerText;
var text = $(this).val();
text.replace(/#$/ , selectedElement);
$(this).val(text);
}
$(document).ready(function() {
$("textarea#autocomplite").autocomplete({
source: function(request, response) {
$.ajax({
url: "/feeds/autocomplite_search",
data: {
term: request.term.substr(getSign(request.term)+1,request.term.length-getSign(request.term)).trim()
},
success: function(data){
for(i=0; i<data.length; i++){
data[i] = '#'+data[i];
}
return response(data);
}
});
},
minLength: 2,
delay: 400,
disabled: true,
search: function() {
if ( /\s$/.test($(this).val()) ) {
$(this).autocomplete('disable');
};
},
select: changeText
});
$("textarea#autocomplite").keyup(function() {
if ( /#$/.test($(this).val()) ) {
$(this).autocomplete('enable');
};
});
});
replace does not modify the original. Reassign:
text = text.replace(/#$/ , selectedElement);

Categories

Resources