To make sure the question more clear,
I want to re-implement the prompt object in JAVASCRIPT because i want to get two variables from the user at the same time.
If it is possible to extend, re-implement or override this object, please tell me how. If not, do you have better solutions?
Thanks.
You should use something like http://jqueryui.com/demos/dialog/#modal-form
You will need to split your javascript where you have your dialog
So if you had
function getAndUseUserInfo() {
bla1();
bla2();
var x = prompt("Gimme something for bla 3","");
if (x) bla3(x); // this will not be executed until user closes prompt
}
you now need
function getUserInfo() {
bla1();
bla2();
var x = "";
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"OK": function() { x = $("#someIdFromtheForm").val(); $(this).dialog("close");}
"CANCEL": function() { $(this).dialog("close");}
}
close: function() {
if (x) bla3(x);
}
});
}
Or if you insist to override the built-in function you can do something like this (which currently gives an error since I am not using an html page):
var orgPrompt = window.prompt;
var varone, vartwo;
function saveVars(doc) {
varone = doc.getElementById("x").value;
vartwo = doc.getElementById("y").value
return [varone,vartwo];
}
window.prompt=function(one,two) {
var html = '<center><br><br>'+one+':<input type=text id=x><br>'+two+':<input type=text id=y><br><input type=button value=OK onclick=\'window.returnValue=window.dialogArguments.saveVars(document);window.close()\'/>';
var res = showModalDialog('javascript:"'+html+'"',window,"dialogWidth:100px;dialogHeight:100px");
}
x = prompt('first name','last name')
alert(x)
You can have them separate the two different values using a delimiter.
var result = prompt('enter two values seperated by a comma').split(',');
alert('first value: ' + result[0]);
alert('second value: ' + result[1]);
DEMO
You can redefine most things in javascript, including the window prompt, alert and confirm methods, but it would probably be a better idea to define the method and call it instead of the native object. Define 'prompter','alerter' or 'confirmer' methods, for example.
Related
I m trying to change the string value of a textarea dynamically. In my code setValue function supposed to do it but whenever i try,the text area is being changed but getting not editable afterwards.
What could cause the problem ?
function createScriptPanel(value, container, mode) {
var scriptPanel = $('<div id="editor"><textarea id="editor-code">' + value.script + '</textarea></div>').appendTo(container);
CodeMirror.commands.autocomplete = function (cm) {
CodeMirror.showHint(cm, CodeMirror.hint.anyword);
};
sincapp.codeEditor = CodeMirror.fromTextArea(document.getElementById("editor-code"), {lineNumbers: true, matchBrackets: true, extraKeys: {"Ctrl-Space": "autocomplete"}, mode: mode});
scriptPanel.getValue = function () {
return sincapp.codeEditor.getValue();
};
scriptPanel.setValue = function (newName,oldName) {
var newValue= sincapp.codeEditor.getValue().replace(newName,oldName);
$('#editor:nth-child(1)').html(newValue);
};
return scriptPanel;
}
Because you are calling html instead of val
instead of $('#editor:nth-child(1)').html(newValue);
say $('#editor:nth-child(1)').val(newValue);
It wasnt about the textarea but about CodeMirror, my mistake. Actually this worked pretty simple for me :
sincapp.codeEditor.setValue(newValue)
Try something like this,
var newValue = sincapp.codeEditor.getDoc().setValue(newName);
I´m building a jQuery extension plugin with the following standard:
(function ($) {
var version = "1.1.0";
var active = false;
$.fn.inputPicker = function (options) {
return this.each(function () {
if ($(this)[0].tagName !== 'DIV')
throw new ReferenceError('mz.ui.dialog.dateTimePicker: Method works only on DIV types.');
/// Label
var labelObj = $("<label class='small'>Data Hora Inicial</label>");
$(this).append(labelObj);
/// Input
var inputObj = $("<input type='datetime-local' class='form-control input-sm'></input>");
$(this).append(inputObj);
})
});
};
}(jQuery));
And here is how I call it:
<div id='test'></div>
$('#test').inputPicker();
Later in code I wanna get the data that was entered in the input field, something like:
$('test').inputPicker().getInputData();
What´s the best way to accomplish that ? I´ve tried something like:
this.getInputData = function () {
return $(inputObj).val();
}
But got errors when calling the function.
Can someone help me with this ? Thanks in advance...
You could just make another method to get the input data like this using the DOM structure and class names that you added:
$.fn.getInputData = function() {
return this.eq(0).find("input.input-sm").val();
}
This would operate only on the first DOM element in the jQuery object (since it's returning only a single value).
So, after setting it up like you did:
$("#test").inputPicker();
You'd then retrieve the data like this:
var data = $("#test").getInputData();
If I have an element on the page like this ...
<span data-function="DoSomething">Click</span>
... and i put this in my page header ...
$(document).ready(function()
{
$('[data-function]').each(function()
{
var fName = $(this).attr('data-function');
$(this).click(fName);
});
});
... what goes in place of the comment produce the desired effect of executing the function called "DoSomething".
Note:
I no the code above wont work, my question is how to make this work (translate 'DoSomething' in to DoSomething();)
Any ideas guys?
The functions should be available. Try putting them in an Object, like this:
$(document).ready(function()
{
var fns = {
DoSomething: function() {/* ... */},
DoAnotherthing: function() {/* ... */}
};
$('[data-function]').each(function()
{
var fName = $(this).attr('data-function');
$(this).click(fns[fName]);
});
});
Here's a jsfiddle, demonstrating a way to keep everything local to one namespace and assigning handlers based on the data attribute of elements.
Try calling function with window object -
$(document).ready(function() {
$('[data-function]').each(function() {
var fName = $(this).attr('data-function');
if (typeof (window[fName]) === "function") {
$(this).click(window[fName]);
}
});
}
You can use something like
$(this).click(window[fName]);
Where window would be replaced by the appropriate expression if the function DoSomething is not defined in the global scope.
Maybe a little bit clean way:
http://jsfiddle.net/whsPG/
var myfuncs = {
alert : function() {
alert("An Alert");
},
changeName: function(obj) {
$(obj).text('Other Text');
}
};
$('[data-function]').on('click', function()
{
value = $(this).data('function');
if (myfuncs.hasOwnProperty(value)) {
myfuncs[value](this);
}
});
I need to implement a confirm box replacement by using jquery dialog. I have a calling function like this
function callingFunc() {
var a = confirmJquery("text", 300, 300, "ok", "cancel");
if (a == true) {
.....
}
else {
....
}
}
This is the confirmJquery function
function confirmJquery(msg, width, height, txtOk, txtCancel) {
var div = document.createElement('div');
div.className = "confirmJquery";
var span = document.createElement('span');
$(span).html(msg);
div.appendChild(span);
var buttonOk = document.createElement('button');
buttonOk.className = 'buttonStyleBigger';
$(buttonOk).html(txtOk);
var buttonCancel = document.createElement('button');
buttonCancel.className = 'buttonStyleBigger';
$(buttonCancel).html(txtCancel);
var divBottom = document.createElement('div');
divBottom.className = 'dialogAction';
divBottom.appendChild(buttonOk);
divBottom.appendChild(buttonCancel);
div.appendChild(divBottom);
var dialog = window.parent.$(div).appendTo(window.parent.document.body);
// open the dialog
dialog.dialog({
height: height,
width: width,
resizable: false,
// add a close listener to prevent adding multiple divs to the document
close: function(event, ui) {
// remove div with all data and events
dialog.remove();
},
modal: true
});
$(buttonOk).bind('click', function(){
return true;
});
$(buttonCancel).bind('click', function() {
return false;
});
}
The problem is, the confirmJquery function always finish before the button (Ok or Cancel) is pressed; hence, there is no value in the calling function. I need to make the confirmJquery waits until user press the button and then function finish and the rest of the calling function continues. How can i do that ?
I need to update more details: I already tried the call back function way. It works perfectly. But, life is not easy like that. This is a very big, old, messy system. Doing that requires me to re-write lot lot of functions, so i need to create a function that act exactly like the confirm function of javascript
Since your function is going to be asynchronous, you need to use a callback. Something like this:
function myCallback(result)
{
if (result) {
// OK
} else {
// Cancel
}
}
function confirmJquery(msg, width, height, txtOk, txtCancel, callback) {
...
$(buttonOk).bind('click', function(){
callback(true);
});
$(buttonCancel).bind('click', function() {
callback(false);
});
}
and
confirmJquery(msg, width, height, txtOk, txtCancel, myCallback);
Move the rest of the function inside another function, and execute that second function at the end of the confirmJquery function.
function firstfunction(){
// Do Some Stuff
secondfunction();
}
first, to avoid a long list of arguments on the receiving side, you can use an object of arguments instead. then send over a callback to confirmJquery
function callingFunc() {
var a = confirmJquery({
msg:"text",
width:300,
height:300,
txtOk:"ok",
txtCancel:"cancel"
},function(ok){
if(ok){
...
} else {
...
}
});
}
function confirmJquery(options,callback) {
//options.msg
//options.width
...
$(buttonOk).bind('click', function(){
callback(true);
});
$(buttonCancel).bind('click', function() {
callback(false);
});
}
yes, alexander is right, just reorganize code, one for dialog, one for function based on a flag/msg. just like mvc pattern.
I'm looking to create a generic confirmation box that can be used by multiple widgets easily, but I'm running into problems with scope and was hoping for a clearer way of doing what I'm trying to do.
Currently I have the following -
(function() {
var global = this;
global.confirmationBox = function() {
config = {
container: '<div>',
message:''
}
return {
config: config,
render: function(caller) {
var jqContainer = $(config.container);
jqContainer.append(config.message);
jqContainer.dialog({
buttons: {
'Confirm': caller.confirm_action,
Cancel: caller.cancel_action
}
});
}
}
} //end confirmationBox
global.testWidget = function() {
return {
create_message: function(msg) {
var msg = confirmationBox();
msg.message = msg;
msg.render(this);
},
confirm_action: function() {
//Do approved actions here and close the confirmation box
//Currently not sure how to get the confirmation box at
//this point
},
cancel_action: function() {
//Close the confirmation box and register that action was
//cancelled with the widget. Like above, not sure how to get
//the confirmation box back to close it
}
}
}//end testWidget
})();
//Create the widget and pop up a test message
var widget = testWidget();
widget.create_message('You need to confirm this action to continue');
Currently I'm just looking to do something as simple as close the box from the within the widget, but I think I've wrapped my own brain in circles in terms of what knows what.
Anyone want to help clear my befuddled brain?
Cheers,
Sam
The resulting code:
I thought it might be useful for people who find this thread in later days looking for a solution to a similar problem to see the code that resulted from the helpful answers I got here.
As it turns out it was pretty simple in the end (as most of the frustrating mind-tangles are).
/**
* Confirmation boxes are used to confirm a request by a user such as
* wanting to delete an item
*/
global.confirmationBox = function() {
self = this;
config = {
container: '<div>',
message: '',
}
return {
set_config:config,
render_message: function(caller) {
var jqContainer = $(config.container);
jqContainer.attr('id', 'confirmation-dialog');
jqContainer.append(config.message);
jqContainer.dialog({
buttons: {
'Confirm': function() {
caller.confirm_action(this);
},
Cancel: function() {
caller.cancel_action(this);
}
}
});
}
}
} // end confirmationBox
global.testWidget = function() {
return {
create_message: function(msg) {
var msg = confirmationBox();
msg.message = msg;
msg.render(this);
},
confirm_action: function(box) {
alert('Success');
$(box).dialog('close');
},
cancel_action: function(box) {
alert('Cancelled');
$(box).dialog('close');
}
}
}//end testWidget
You could pass jqContainer to the confirm/cancel functions.
Alternately, assign jqContainer as a property of caller. Since the confirm/cancel functions are called as methods of caller, they will have access to it via this. But that limits you to tracking one dialog per widget.
Try something like this:
(function() {
var global = this;
/*****************This is new****************/
var jqContainer;
global.confirmationBox = function() {
config = {
container: '<div>',
message:''
}
return {
config: config,
render: function(caller) {
// store the container in the outer objects scope instead!!!!
jqContainer = $(config.container);
jqContainer.append(config.message);
jqContainer.dialog({
buttons: {
'Confirm': caller.confirm_action,
Cancel: caller.cancel_action
}
});
}
}
} //end confirmationBox
global.testWidget = function() {
return {
create_message: function(msg) {
var msg = confirmationBox();
msg.message = msg;
msg.render(this);
},
confirm_action: function() {
//Do approved actions here and close the confirmation box
//Currently not sure how to get the confirmation box at this point
/*******Hopefully, you would have access to jqContainer here now *****/
},
cancel_action: function() {
//Close the confirmation box and register that action was
//cancelled with the widget. Like above, not sure how to get
//the confirmation box back to close it
}
}
}//end testWidget
})();
//Create the widget and pop up a test message
var widget = testWidget();
widget.create_message('You need to confirm this action to continue');
If that doesn't work, try defining your callbacks (confirm_action, cancel_action) as private members of your object. But they should be able to access the outer scope of your main object.