jQuery .remove() not working - javascript

I have an script that uses datatables and keytables scripts, and when user clicks in a button I launch a jQuery UI dialog to confirm delete one row of the table. The row is deleted correctly of the database by AJAX and fadeOut of the table, but I don't know why the row is not removed from the DOM. Here is dialog code:
$('#delConfDialog').dialog({
autoOpen : false,
modal : true,
beforeClose : function(event, ui) {
setTimeout(function() {
keys = new KeyTable({
"table" : document.getElementById('records'),
"datatable" : dataTable,
"focus" : tableFocus
});
keys.fnSetPosition(currentPosition[0], currentPosition[1]);
addTableEvents();
}, 50);
},
buttons : {
'Cancelar' : function() {
$(this).dialog('close');
},
'OK' : function() {
$('#ajaxLoadAni').fadeIn('fast');
$(this).dialog('close');
eliminar = elementoEliminar;
delHref = eliminar.attr('delete');
currentPosition[1] = currentPosition[1] + 1;
$.ajax({
url : delHref,
success : function(response) {
$('#ajaxLoadAni').fadeOut('fast');
eliminar.fadeOut("fast", function() {
eliminar.remove();
});
}
});
}
}
});

The problem could be the use of a global variable
try
var eliminar = elementoEliminar;
eliminar.fadeOut("fast", function () {
eliminar.remove();
});

Related

Show popover upon hover on an icon in a datatable

I generate my datatable in an .ashx file:
(...)
//E.g. This is how I generate an icon which I put into one of the table cells
comment = "<i class=\"fa fa-info\" id=\"popoverData\"aria-hidden=\"true\" data-placement=\"bottom\" data-original-title=\"Comments\" data-content=\"" + comments_text + "\"></i>";
(...)
var data = JsonConvert.SerializeObject(data);
var columns = JsonConvert.SerializeObject(columns);
context.Response.Write("{\"data\":" + data + ",\"columns\":" + columns + "}");
The goal is to show a bootstrap popover upon hover on the above icon. My JavaScript:
$(document).ready(function (){
//this part should generate the bootstrap popover, but it's NOT
$('#MyDataTable').on('mouseover', '#popoverData', function () {
$('#popoverData').popover();
//console log gets activated
console.log("I am in the function");
});
getData();
});
function getData() {
$('#MyDataTableDiv').html('<table id="MyDataTable" class="display" cellspacing="0" width="100%"></table>');
$.ajax({
"url": myUrl/getData.ashx',
"success": function (json) {
json.columnDefs = [
{ targets: '_all', defaultContent: "" },
{ targets: '_all', className: 'dt-body-left' }
];
json.dom = 'Bfrtip';
json.buttons = ['print', 'csv', 'copy'];
$('#MyDataTable').dataTable(json);
},
"dataType": "json"
});
}
The javascript mouseover event gets triggered, but the popover is not working. I've tried this too:
$(document).ready(function (){
$('#popoverData').popover();
getData();
});
But in this case the popover shows up ONLY if the #popoverData element is outside the datatable.
How do I show popover upon hover on the icon?
Please modify your code.
$('#MyDataTable').on('mouseover', '#popoverData', function () {
$(this).popover('show');
});
if this not worked then try
$(document).on('mouseover', '#popoverData', function () {
$(this).popover('show');
});

Wait for document mousedown to complete before element onclick can start

I have a panel that slides open on an element click called "details" and populates the panel via ajax depending on the data attribute value. I also have it setup that if you close outside that panel, it will close. If the panel is open and the user clicks on a different "details" element, I want the panel to close and open again populated with the data from the new data attribute.
Problem is that the codes checks if the panel is visible and won't load the ajax if it is. How can I change this so the click event knows the mousedown event is completed before it does it's thing?
// SLIDING PANEL
$(".details").on("click", function(e){
e.preventDefault();
var panel = $("#DetailsPanel");
var mkey = $(this).data("masterkey-id");
var _self = $(this);
// fetch data ONLY when panel is hidden...
// otherwise it fetches data when the panel is closing
if (!panel.is(':visible')) {
panel.load("/com/franchise/leads.cfc?method=getLeadDetails", { mkey: mkey }, function(response, status, xhr) {
// if the ajax source wasn't loaded properly
if (status !== "success") {
var msg = "<p>Sorry, but there was an error loading the document.</p>";
panel.html(msg);
};
// this is part of the .load() callback so it fills the panel BEFORE opening it
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().addClass("warning");
});
});
} else {
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().removeClass("warning");
});
};
return false;
});
$(document).on("mousedown", function(){
$("#DetailsPanel").hide("slide", { direction: "right" }, "fast", function(){
//_self.parent().parent().removeClass("warning");
});
});
// don't close panel when clicking inside it
$(document).on("mousedown","#DetailsPanel",function(e){e.stopPropagation();});
$(document).on("click", "#ClosePanel", function(){
$("#DetailsPanel").hide("slide", { direction: "right" }, "fast", function(){
$("#LeadsTable tr").removeClass("warning");
});
});
// END SLIDING PANEL
Setting a timeout worked for me in another context:
onclick="window.setTimeout( function(){ DO YOUR STUFF }, 2);"
This solves many problems of this type.
I'm not totally sure about this but if you use "mouseup" instead "click" could work as you expect. Try it and let me know if I'm wrong.
Ok, so I found this little nugget http://www.gmarwaha.com/blog/2009/06/09/jquery-waiting-for-multiple-animations-to-complete/ and it works pretty good. No issues so far.
Here is the new code
$(".details").on("click", function(e){
e.preventDefault();
var panel = $("#DetailsPanel");
var mkey = $(this).data("masterkey-id");
var _self = $(this);
// fetch data ONLY when panel is hidden...
// otherwise it fetches data when the panel is closing
var wait = setInterval(function() {
if( !$("#DetailsPanel").is(":animated") ) {
clearInterval(wait);
// This piece of code will be executed
// after DetailsPanel is complete.
if (!panel.is(':visible')) {
panel.load("/com/franchise/leads.cfc?method=getLeadDetails", { mkey: mkey }, function(response, status, xhr) {
// if the ajax source wasn't loaded properly
if (status !== "success") {
var msg = "<p>Sorry, but there was an error loading the document.</p>";
panel.html(msg);
};
// this is part of the .load() callback so it fills the panel BEFORE opening it
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().addClass("warning");
});
});
} else {
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().removeClass("warning");
});
};
}
}, 200);
return false;
});

Call magnificPopUp within another function

I would like to display a magnific popup within another functions onclick event. This function has a conditional statement and if false, then the pop-up should be displayed.
I have created a jsfiddle which shows what I am trying to do: http://jsfiddle.net/Lilu/heM4q/
Html:
<button class="add-wishlist"><span>Wishlist</span></button>
Jquery:
$(document).on('click', '.add-wishlist', function(e) {
var yes = "1";
if (yes == "2"){
// Add to wishlist
}else {
// Display error in popup
$.magnificPopup.open({
type: 'ajax',
alignTop: true,
mainClass: 'my-mfp-zoom-in',
removalDelay: 160,
callbacks: {
parseAjax: function(mfpResponse) {
mfpResponse.data = "<div class='modal-content'>"+"Sorry you cannot do that"+"</div>";
},
ajaxContentAdded: function() {
return this.content;
}
}
});
}
});
Any help will greatly be appreciated.
I found out that I can achieve the pop-up using inline magnific pop-up instead of ajax.
HTML:
<button class="add-wishlist"><span>Wishlist</span></button>
JQuery:
$(document).on('click', '.add-wishlist', function(e) {
var yes = "1";
if (yes == "2"){
// Add to wishlist
}else {
// Display error in popup
displayError();
}
});
function displayError() {
$.magnificPopup.open({
items: {
src: '<div class="modal-content">'
+'<p class="error">'
+'<strong>Whoops!</strong></p>'
+'<p>You cannot do that.</p></div>',
type:'inline',
},
closeBtnInside: true
});
}
Please see: http://jsfiddle.net/Lilu/heM4q/4/

jQuery ajax form submitting multiple times

I am having some issues with multiple form submissions with a jQuery/ajax form. I found this by printing every instance of form submission on my server, and saw that a form would submit correctly once, then again multiple times.
Just to be clear, this code works 100% correctly for the first submission, but when I click on another row in my table, and create a new dialog/submit it, it ends up submitting multiple times.
I think it has to do with event binding, but am having trouble fixing it. Any insight or help would be much appreciated.
The button's id is "save-flag-button"
// When someone clicks on the flag column in my table, a dialog pops up //
// on the condition that a flag does not exist. //
$(function() {
$('.flag').click(function() {
var cellId = "flag" + String(this.getAttribute("data-client-rel"));
if (this.getAttribute("data-flag-exists") == '0') {
// create dialog
var dialog = flagDialog('Create Flag');
// Making the form ajax
$("form", dialog).ajaxForm(function(success, data) {
if (success) {
$("#" + cellId).attr("data-flag-exists", '1');
$("#" + cellId).attr("data-flag-content", data["flag_state"]);
$("#" + cellId).text(data["flag_state"]);
$("#flag-dialog").dialog("close");
} else {
alert("Failed to submit flag. Please retry.");
}
});
} else { }
}).hover(function() {
if (this.getAttribute("data-flag-exists") == '0') {
this.innerHTML = '<span style="color: #4183C4;">Create flag!</span>';
}}, function() {
this.innerHTML = this.getAttribute("data-flag-content");
})
});
// jquery dialog code //
function flagDialog(dialogTitle) {
var dialog = $("#flag-dialog").dialog({
autoOpen: false,
autoResize: true,
modal: true,
minHeight: 300,
minWidth: 450,
position: "center",
title: dialogTitle,
buttons: [{
id: "flag-cancel-button",
text: "Cancel",
click: function() {
$(this).dialog("close");
}
},
{
id:"save-flag-button",
text: "Submit",
click: function() {
$("#flag-dialog").dialog("destroy");
// $("#client-relationship-flag-form").submit();
}
}],
close: function() {
//$("#notes-text").text("");
}
});
// Unbinding buttons here //
$("#save-flag-button, #flag-cancel-button").unbind();
$("#save-flag-button").unbind('click').click(function() {
$("#client-relationship-flag-form").submit();
});
$("#flag-cancel-button").click(function() {
$("#flag-dialog").dialog("close");
});
dialog.dialog("open");
return dialog;
};
ajaxForm binding should be done once only.
Try to put the ajaxForm binding on $(document).ready event and try to restructure your logic. ajaxForm was bind every time you click .flag element and all previously bind ajaxForm would be called on all succeeding click event.

Dialog pop up doesn't close

I'm trying to create a dialog box that adds an item to a dropdownlist;
here's the code.
$(function () {
$('#applicantDialog').dialog({
autoOpen: false,
width: 600,
height: 500,
modal: true,
title: 'Add Applicant',
buttons: {
'Save': function () {
var createApplicantForm = $('#createApplicantForm');
if (createApplicantForm.valid()) {
$.post(createApplicantForm.attr('action'), createApplicantForm.serialize(), function (data) {
if (data.Error != '') {
alert(data.Error);
}
else {
// Add the new Applicant to the dropdown list and select it
$('#Applicant').append(
$('<option></option>')
.val(data.id_applicant)
.html(data.Applicant.Applicant_name)
.prop('selected', true) // Selects the new Applicant in the DropDown LB
);
$('#applicantDialog').dialog('close');
}
});
}
},
'Cancel': function () {
$(this).dialog('close');
}
}
});
$('#applicantAddLink').click(function () {
var createFormUrl = $(this).attr('href');
$('#applicantDialog').html('')
.load(createFormUrl, function () {
// The createGenreForm is loaded on the fly using jQuery load.
// In order to have client validation working it is necessary to tell the
// jQuery.validator to parse the newly added content
jQuery.validator.unobtrusive.parse('#createApplicantForm');
$('#applicantDialog').dialog('open');
});
return false;
});
});
My problem is that when the form is saved and the item is added, it never closes the dialog box. When I click on cancel, the list is not updated until I refresh the page.
Is it a problem with postback and how can I deal with that?
Thanks

Categories

Resources