Skip to content Skip to sidebar Skip to footer

Is It Possible To Extend Prompt() Object In Javascript

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 t

Solution 1:

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

functiongetUserInfo() {
  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;
  functionsaveVars(doc) {
    varone = doc.getElementById("x").value;
    vartwo = doc.getElementById("y").valuereturn [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)

Solution 2:

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

Solution 3:

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.

Post a Comment for "Is It Possible To Extend Prompt() Object In Javascript"