Call magnificPopUp within another function - javascript

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/

Related

jQuery ("#dialog").dialog('close') not working with button on separate view

I have an ASP.NET view in an MVC project in which I am trying to create a pop-up dialog to create data. There is another view that gets loaded and that view has a button with the id "btncancel_create". I cannot get that button to close the dialog. I am using jQuery 2.1.3 and jQuery UI 1.11.4.
Here is the code for the button:
<input type="button" value="Cancel" id="btncancel_create" />
And here is the view:
$(document).ready(function () {
//alert("Document is ready");
var url = "";
$("#dialog-create").dialog({
title: 'Create User',
autoOpen: false,
resizable: false,
width: 400,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(".ui-dialog-titlebar-close").hide();
$(this).load(url);
}
});
$("#lnkCreate").on("click", function (e) {
url = $(this).attr('href');
$("#dialog-create").dialog('open');
return false;
});
//$("#btncancel_create").on("click", function (e) {
// $("#dialog-create").dialog("close");
// return false;
//});
$("#dialog-create").button("#btncancel_create").click(function (e) {
alert("btncancel_create was clicked");
$("#dialog-create").dialog('close');
return false;
});
});
<div id="dialog-create" style="display: none"></div>
<p>#Html.ActionLink("Create New", "Create", null, new { id = "lnkCreate" })</p>
As you can see, I tried something else which didn't work, which is commented out. The uncommented button click function does return the alert, but does not close the dialog. Thanks in advance for your help, and please let me know if you need any more information.
Instead of
$("#btncancel_create").on("click", function (e) {...
(in my commented out code above)
it should be
$(document).on("click", "#btncancel_create", function (e) {....
I found the answer here: Turning live() into on() in jQuery.

Clicking on element from jQuery dialog generated by function

I am having a rather strange issue with jQuery/Javascript. (This happens in IE, FF and Chrome)
I have a (asp.net) webpage as follows:
Header with lots of buttons (generated at PreRender)
Hidden div with buttons doing postbacks (generated OnLoad) & a div to use as a dialog
Page with an iFrame
Lets say I have a Button with '1234_stuff' as its CLIENTID in the Hidden div.
I have a button in the Header that has a OnClientClick = "$('#1234_stuff').click();return false;";
When I click the button that is in the header this works perfectly. Good.
I have an other button in the header (lets call it PopupStarter) that has a OnClientClick = "Popup('Titel', 'Description', '1234_stuff');return false;";
The javascript Popup function is as follows:
function Popup(title, description, buttonid) {
$('#dialog-popupText').html('<p><b>' + title + '</b></p><p>' + description + '</p>');
var buttonsToShow;
if (buttonid!= null) {
buttonsToShow = {
'ClickMe': function () {
$('#' + buttonid).click();
$(this).dialog('close');
},
'Cancel': function () {
$(this).dialog('close');
}
}
} else {
buttonsToShow = {
'Cancel': function () {
$(this).dialog('close');
}
}
}
$('#dialog-popup').dialog(
{
resizeable: false,
width: 'auto',
modal: true,
draggable: false,
buttons: buttonsToShow
});
}
When I click the 'PopupStarter' button the jQuery dialog shows as expected, no trouble there. However... when I click the ClickMe button nothing happens (besides closing the dialog).
I would think I did something wrong: so I tried it with a timer:
function Popup(title, description, buttonid) {
$('#dialog-popupText').html('<p><b>' + title + '</b></p><p>' + description + '</p>');
var buttonsToShow;
if (buttonid!= null) {
buttonsToShow = {
'ClickMe': function () {
setTimeout(""$('#"" + buttonid + ""').click();"", 100);
$(this).dialog('close');
},
'Cancel': function () {
$(this).dialog('close');
}
}
} else {
buttonsToShow = {
'Cancel': function () {
$(this).dialog('close');
}
}
}
$('#dialog-popup').dialog(
{
resizeable: false,
width: 'auto',
modal: true,
draggable: false,
buttons: buttonsToShow
});
}
This works!! Now that is odd. So I called the parent jQuery
parent.$('#' + buttonid).click();
This also does not work.
And to top it all off, when I enter each of the lines manually in the console of the browser they all work!
Try using this:
$(document).on('click', '#' + buttonid, function(){
Your functions here;
});
Any items that do not exist on page load, will need to have the event listeners applied to the document, the body, or any parent selector that existed in the DOM on page load. Javascript does not attach listeners to objects that are not present when the DOM is loaded. Hope this helps!

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.

Javascript/Jquery Callback for Fancybox Yes No Confirm

I'm trying to implement a fancy Yes No confirm and I'm having problems getting the callback to work as needed. The example below is using Fancybox v2.
The problem with the code below is that the function "do_something" is being call when HREF "Test" is clicked and not being called when the user clicks #fancyConfirm_ok.
function fancyConfirm(msg,callback) {
var ret;
jQuery.fancybox({
'modal' : true,
'content' : "<div style=\"margin:1px;width:240px;\">"+msg+"<div style=\"text-align:right;margin-top:10px;\"><input id=\"fancyconfirm_cancel\" style=\"margin:3px;padding:0px;\" type=\"button\" value=\"Cancel\"><input id=\"fancyConfirm_ok\" style=\"margin:3px;padding:0px;\" type=\"button\" value=\"Ok\"></div></div>",
'afterShow' : function() {
jQuery("#fancyconfirm_cancel").click(function() {
ret = false;
//jQuery.fancybox.close();
$.fancybox.close();
})
jQuery("#fancyConfirm_ok").click(function() {
ret = true;
jQuery.fancybox.close();
})
},
'afterClose' : function() {
if (typeof callback == 'function'){
callback.call(this, ret);
} else {
var callback_type = typeof callback;
alert(callback_type);
}
}
});
}
Test
Your method "do_something('a', 'b')" will be executed whenever user clicks on the link and the returned result will be passed as the second parameter to the "fancyConfirm" method. This is why your parameter "callback" is always "undefined".
There is also a problem with fancyBox - "afterClose" callback gets called twice - before opening and after closing (this will be changed in the next release).
I would bind a click event on the link and call a callback when user clicks on one of the buttons, like - http://jsfiddle.net/xcJFY/1/
Not a big fan of the double callback method (Sorry Janis).
So while trying to find a solution to this myself played around with similar code and found that as long my return value wasn't defined inside the scope of the function it works fine, when my return value was defined inside the function I would get weird behaviour where it would work for a time then revert to undefined.
Effectively the return value needs to be outside the scope of the function, global, closure etc.
$(document).ready(function() {
$(".fancybox").on("click", function(e){
e.preventDefault();
confirm("Do you wish to continue?", true, function(resp) {
alert("You clicked " + resp);
});
});
});
function confirm(msg, modal, callback) {
$.fancybox("#confirm",{
modal: modal,
beforeShow: function() {
$(".title").html(msg);
},
afterShow: function() {
$(".confirm").on("click", function(event){
if($(event.target).is(".yes")){
ret = true;
} else if ($(event.target).is(".no")){
ret = false;
}
$.fancybox.close();
});
},
afterClose: function() {
callback.call(this, ret);
}
});
}
Here is a jsfiddle example
Thanks to Francisco Diaz who's post on Google Groups FancyBox forum pointed me in the right direction.
UPDATE:
Have now extended my example to use dynamically built buttons and custom return values, so you are not just limited to true and false.
$(document).ready(function() {
$(".fancybox").on("click", function(e){
e.preventDefault();
confirm("Do you wish to continue?", {
/*
Define your buttons here, can handle multiple buttons
with custom title and values
*/
buttons: [
{ class: "yes", type: "button", title: "Yes", value: "yes" },
{ class: "no", type: "button", title: "No", value: "no" },
{ class: "maybe", type: "button", title: "Maybe?", value: "maybe" }
],
modal: true
},
function(resp) {
alert("You clicked " + resp);
}
);
});
});
function confirm(msg, options, callback) {
$.fancybox("#confirm",{
modal: options.modal,
beforeShow: function() {
this.content.prepend("<p class=\"title\"></p>");
$(".title").html(msg);
for (i = 0; i < options.buttons.length; i++) {
this.content.append($("<input>", {
type: "button", class: "confirm " + options.buttons[i].class,
value: options.buttons[i].title
}).data("index", i));
}
},
afterShow: function() {
$(".confirm").on("click", function(event){
ret = options.buttons[$(event.target).data("index")].value;
$.fancybox.close();
});
},
afterClose: function() {
this.content.html("");
callback.call(this, ret);
}
});
}
Added jsfiddle example

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