Is it possible to extend prompt() object in JAVASCRIPT

不想你离开。 提交于 2019-11-29 11:53:17

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!