jQueryUI dialog wth dynamic buttons using callbacks - javascript

I am using this question as the basis for a multipurpose jQueryUI dialog function that I can reuse in my site Question 17013222 I want to be able to reuse the code to display different buttons with callbacks defined in the function call
However, I don’t get the result I need when extending this answer to use a callback function. The callback function is running as I build the dynamic buttons instead of when the Dialog Save button is pressed.
I have a jsFiddle here that shows my incompetence jsFiddle
What do I need to do to get the callback to run as the Save button is clicked?
Below is the simplified code snippet
function showDialog(inToDisplay, inTitle, buttonSetup, inSaveCallback) {
'use strict';
var dialog_buttons = {};
$('#jqDialog').load(inToDisplay + '.asp', function () {
$(this).attr('title', inTitle);
/*Build our button choices*/
if (buttonSetup === 'closeonly') {
dialog_buttons['Close'] = function () {
$(this).dialog("close");
$(this).dialog("destroy");
}
} else if (buttonSetup === 'savecancel') {
dialog_buttons['Save'] = function () {
if (inSaveCallback && typeof (inSaveCallback) === "function") {
inSaveCallback;
};
$(this).dialog("close");
$(this).dialog("destroy");
}
dialog_buttons['Close'] = function () {
$(this).dialog("close");
$(this).dialog("destroy");
}
}
$(this).dialog({
autoOpen: false,
modal: true,
open: function (event, ui) {
},
buttons: dialog_buttons
});
$('#jqDialog').dialog('open');
});
}
function saveAnswer() {
alert('ToDo: Save data here');
}
$(document).ready(function () {
showDialog('ajax_manageAnswer', 'Enter your answer details', 'savecancel', saveAnswer());
});

here... http://jsfiddle.net/reigel/zpyNM/
change this
$(document).ready(function () {
showDialog('ajax_manageAnswer', 'Enter your answer details', 'savecancel', saveAnswer); // remove () on saveAnswer...
});
and this
dialog_buttons['Save'] = function () {
if (inSaveCallback && typeof (inSaveCallback) === "function") {
inSaveCallback(); // add -->> ()
};
$(this).dialog("close");
$(this).dialog("destroy");
}

Related

jquery dialog cause other function not working

I have a OK button, when click it, it calls hideTyre(). the hideTyre() function calls SetBankFees function.
I also have $("#dialog-immpay").dialog() and $("#dialog-SelectFees").dialog().
The problem is that when I place hideTyre() before the two dialog(), OK button click cannot found the hideTyre(),
if I place the hideTyre() after the two dialog(), then hideTyre() is executed, but I got another error, it says the SetBankFees() is undefined.
Although the two dialog() work fine here, I guess the two dialog() cause the problem. But I could not figure out whats wrong there.
I appreciate your help very much.
<script>
...more js functions
function SetBankFees()
{
`enter code here` }
`enter code here` ...more js functions
function hideTyre()
{
SetBankFees();
$("#tyreDiv").hide();
$(".main").show();
}
var immPayF8OrF9 = "";
$("#dialog-immpay").dialog({
autoOpen: false,
height: 400,
width: 750,
modal: true,
dialogClass: "no-close",
buttons: {
"Save without Print Invoice": function () {
allFields.removeClass("ui-state-error");
FImmPay = immPay_Payment;
FComp = immPay_Comp;
FImmPayDate = CCDateStrToJDate($("#datePay").val());
FCompDate = CCDateStrToJDate($("#dateCom").val());
if ((FImmPay > 0.005) || (FComp > 0.005))
{
FSaveImmPay = true;
FImmPayReceipt = immPay_Receipt;
}
else
FSaveImmPay = false;
FPrtInv = immPay_PrtInv;
$(this).dialog("close");
},
"print all unissued invoices": function () {
allFields.removeClass("ui-state-error");
FImmPay = immPay_Payment;
FComp = immPay_Comp;
FImmPayDate = CCDateStrToJDate($("#datePay").val());
FCompDate = CCDateStrToJDate($("#dateCom").val());
if ((FImmPay > 0.005) || (FComp > 0.005))
{
FSaveImmPay = true;
FImmPayReceipt = immPay_Receipt;
}
else
FSaveImmPay = false;
immPayF8OrF9 = "F8";
$(this).dialog("close");
},
"print last invoice only": function () {
allFields.removeClass("ui-state-error");
FImmPay = immPay_Payment;
FComp = immPay_Comp;
FImmPayDate = CCDateStrToJDate($("#datePay").val());
FCompDate = CCDateStrToJDate($("#dateCom").val());
if ((FImmPay > 0.005) || (FComp > 0.005))
{
FSaveImmPay = true;
FImmPayReceipt = immPay_Receipt;
}
else
FSaveImmPay = false;
immPayF8OrF9 = "F9";
$(this).dialog("close");
},
"Esc": function () {
$(this).dialog("close");
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
if (immPayF8OrF9 == "")
DoAfterDoImmPay();
else
ShowOption("#dialog-showPrintingOption", OriInvOption);
}
});
$("#dialog-SelectFees").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Select the fee" : function () {
allFields.removeClass("ui-state-error");
$(this).dialog("close");
AddRow(y);
},
"Cancel" : function(){
allFields.removeClass("ui-state-error");
$(this).dialog("close");
}
}
});
});
// if leave hideTyre() here, then error SetBankFees(); is undefined
// function hideTyre()
// {
// SetBankFees();
// $("#tyreDiv").hide();
// $(".main").show();
// }
...more js functions
</script>
<button onclick="hideTyre()">OK</button>
The problem is function hideTyre() and function SetBankFees() are in different scopes.
SetBankFees() is inside $(function () {}), but hideTyre() is not.
What my findings are the function outside $(function () {}) cannot access the function inside $(function () {}), but function inside $(function () {}) can access the function outside $(function () {}).

jQuery Popup to Delete

I am trying to make a jQuery popup to delete the record from table.
Here's what I am doing to call my function:
echo '<div id="dialog-confirm">'.'<td>' . '<input type="image" src="delete.png" id = "deleteconfirm" style = "height:20px;margin-left :8px;" onclick = "deleterecord('.$row['id'].')">' . '</td>'.'</div>';
And here's my function:
function deleterecord ( id ) {
function fnOpenNormalDialog() {
$("#dialog-confirm").html("Confirm Dialog Box");
// Define the Dialog and its properties.
$("#dialog-confirm").dialog({
resizable: false,
modal: true,
title: "Modal",
height: 250,
width: 400,
buttons: {
"Yes": function () {
$(this).dialog('close');
callback(true);
},
"No": function () {
$(this).dialog('close');
callback(false);
}
}
});
}
$('#deleteconfirm').click(fnOpenNormalDialog);
function callback(value) {
if (value) {
window.location.href = 'delete_ven.php?id=' + id;
} else {
alert("Rejected");
}
}
}
Any help? It's not working.
Your callback method doesn't get any information about row ID. For example you could change following lines:
callback(true);
to
callback(id);
and
window.location.href = 'delete_ven.php?id=' + id;
to
window.location.href = 'delete_ven.php?id=' + value;
Edit: Additionally remove all lines containing "fnOpenNormalDialog" and fix the code accordingly. The click event is assigned in html already, and the function inside function isn't meant work this way.

How can i make a switch button that each click it will do something else?

I'm calling this function from inside a button onclick event:
function pauseSlide() {
clearInterval(sint);
setInterval(slideUpdate, 1000); paused(clearInterval)
}
And i want that on the first click to do the clearInterval(sint);
And if i click on the button again then only do the setInterval(slideUpdate, 1000);
Like a switch.
In csharp for example you do it like this: CelsiusFahrenheit = !CelsiusFarenheit;
So one click the boolean CelsiusFahrenheit is true and next click it's false then again true and so on....
This is the javascript button onclick event:
var
slideShow = d.getElementById('slideShow'),
slideCounter = make('div', false, {id: 'slideCounter'}),
slideControls = make('div', false, {id: 'slideControls'}),
slidePrev = make('a', 'Previous Slide', {
onclick: function (e) {
controlEvent(e, prevSlide);
},
className: 'previous',
href: '#'
}, slideControls),
slideNext = make('a', 'Next Slide', {
onclick: function (e) {
controlEvent(e, nextSlide);
},
className: 'next',
href: '#'
}, slideControls),
slidePause = make('a', 'Pause Slide', {
onclick: function (e) {
controlEvent(e, pauseSlide);
},
className: 'pause',
href: '#'
}, slideControls)
I did that if i click the Pause Slide button it will call the function pauseSlide
And inside pauseSlide i want to make the switch one click to call clearInterval another click will call setInterval.
I have this function also:
function slideUpdate() {
if (swapCounter--)
showCounter();
else
nextSlide();
}
And if i click the button a lot it's just making the countdown to move faster each time.
If it will help or needed this is the complete code with all buttons events:
JS
There are probably a few ways to do this. The best is probably to keep a boolean variable such as "isPaused" and flip that back and forth as needed. Wrap your click logic in a conditional dependent on that variable.
BTW you can't detect whether an interval is running or has been cleared. Even if you could, it would be harder to read and understand what was going on. I'd prefer a semantic variable as described above.
This is example of handle multiactions in loop, main idea is to place actions to array and shift/push them to cycle.
var actions = [
function () {
console.log(1);
$(this).next().fadeOut(100);
},
function () {
console.log(2);
$(this).next().fadeIn(100);
},
function () {
console.log(3);
$(this).next().slideUp();
},
function () {
console.log(4);
$(this).next().slideDown();
}];
$('.multiact').each(function (i, e) {
$(e).data('actions', actions.concat());
}).click(function (e) {
var acts = $(this).data('actions'),
act = acts.shift();
acts.push(act);
act.call(this, e);
});
http://jsfiddle.net/8tgxpedq/2/
var prevClicked = false;
var my_slide_timer;
function pauseSlide() {
if(!prevClicked){
clearInterval(my_slide_timer);
prevClicked = true;
}else{
my_slide_timer = setInterval(slideUpdate, period);
prevClicked = false;
}
}
This did the trick.

How to recall a function with Jquery in this example?

How to recall a function and have the
dialog box keep coming back when click 'cancel' button with Jquery in this example?
I am sure it is easy but still learning some of the basics here.
Thanks
function definitelyClose() {
window.location = 'http://www.google.com'
};
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5000;
var warnPeriod = 10000;
$(document).ready(function() {
$('#proba').dialog({
autoOpen: false
});
setTimeout(function() {
$('#proba').attr('title', 'Warning').text('Sesion will expire').dialog('open');
$('#proba').dialog({
buttons: {
'Cancel': function() {
$(this).dialog('close');
clearTimeout(autoCloseTimer);
}
}
});
autoCloseTimer = setTimeout('definitelyClose()', warnPeriod);
}, timePeriod);
});​
You need to create function with a name to
show the initial warning and
to call when the cancel button is clicked.
So you would get something like this:
$(document).ready(function() {
var autoCloseTimer;
var timePeriod = 5000;
var warnPeriod = 10000;
function definitelyClose() {
window.location = 'http://www.google.com'
};
// You need a function with a name
function showWarning() {
$('#proba').attr('title', 'Warning')
.text('Sesion will expire')
.dialog('open');
$('#proba').dialog({
buttons: {
'Cancel': function() {
$(this).dialog('close');
clearTimeout(autoCloseTimer);
// Now you can recall the function
setTimeout(showWarning, timePeriod);
}
}
});
autoCloseTimer = setTimeout(definitelyClose, warnPeriod);
}
$('#proba').dialog({ autoOpen: false });
setTimeout(showWarning, timePeriod);
});​

jquery UI dialog buttons - return true?

buttons : {
Ok: function() {
$(this).dialog('close');
return (typeof callback == 'string') ?
window.location.href = callback :
callback();
},
Cancel: function() {
$(this).dialog('close');
return false;
}
},
For jquery UI, I need to return values the same as a javascript confirm message a 1 and a 0
I assume I do a callback, but unsure how to reference the callback...
EDIT
jsp developer stated that he doesn't neccessarily need a callback, but needs to be able to do something similar to:
if (answer == true) {
//do something
}
else {
//do something different
}
how would I do that?
You cannot do a return in a jquery dialog.
What you can do:
buttons: {
Ok: function() {
$(this).dialog('close');
callback_fn(1);
},
Cancel: function() {
$(this).dialog('close');
callback_fn(0);
}
},
//later on:
function callback_fn(bool){
//do something with the 1 or 0
}

Categories

Resources