Is it possible to extend prompt() object in JAVASCRIPT
To make sure the question more clear,
I want to re-i开发者_开发问答mplement 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.
精彩评论