I’m trying to create a javascript class which opens a jQuery dialog and allows the user to select an option then returns the selected value in a callback.
…similar to how the jQuery Alert Dialogs do it.
jPrompt(message, [value, title, callback])
jPrompt('Type something:', 'Prefilled value', 'Prompt Dialog', function(r) {
if( r ) alert('You entered ' + r);
});
Here is a DEMO of what i have so far. But if you notice, the value gets set imidiately, and i want it to wait until the user clicks OK. If the user clicks Cancel, then it should return null or empty string.
Here’s my Javascript Class:
var namespace = {};
(namespace.myChooser = function () {
var _dialog = null;
/**
* Function : onButtonCancel
*/
function onButtonCancel() {
_dialog.dialog("close");
return null;
}
/**
* Function : onButtonOK
*/
function onButtonOK() {
_dialog.dialog("close");
}
/**
* Function : Initialize
*/
function Init() {
var dialog_options = {
modal: false,
disabled: false,
resizable: false,
autoOpen: false,
//height: 460,
maxHeight: 300,
zIndex: 500,
stack: true,
title: 'My Chooser',
buttons: { "OK": onButtonOK, "Cancel": onButtonCancel }
};
_dialog = $("#myDialog");
// create dialog.
_dialog.dialog(dialog_options);
_dialog.dialog("open");
}
return {
Choose: function Choose() {
Init();
var myChoice = $("#myOptions").val();
return myChoice;
}
}
}());
And i want to be able to do something like this:
namespace.myChooser.Choose(function (myChoice) {
$("span#myChoice").text(myChoice);
});
SOLUTION:
This is what finally did it:
$(document).ready(function () {
$('#myButton').click(function () {
namespace.myChooser.Choose(function (x) {
console.log(x);
});
});
});
var namespace = {};
(namespace.myChooser = function (callback) {
function _show(callback) {
var dialog_options = {
modal: false,
disabled: false,
resizable: false,
autoOpen: false,
//height: 460,
maxHeight: 300,
zIndex: 500,
stack: true,
title: 'My Chooser',
buttons: {
"OK": function () {
if (callback) callback("OK");
},
"Cancel": function () {
if (callback) callback("Cancel");
}
}
};
_dialog = $("#myDialog");
// create dialog.
_dialog.dialog(dialog_options);
_dialog.dialog("open");
}
return {
Choose: function (callback) {
_show(function (result){
if (callback) callback(result);
});
}
}
}());
Should do what you want