Isaac Dontje Lindell
Isaac Dontje Lindell

Reputation: 3446

Re-implementing Javascript prompt() dialog using modal

I'm tasked with replacing a Javascript prompt call with a custom function that uses a fancy Javascript-activated modal dialog.

The function is called once and expects a string back, with the input from the user. I cannot control how the function is called (it's an external library.)

Making the modal and getting input is easy. How do I return the input to the caller of my custom prompt function after the user clicks the Submit/OK button?

jQuery is fine.

Upvotes: 2

Views: 1018

Answers (2)

Esailija
Esailija

Reputation: 140228

The browser implementation for prompt() is implemented in a way that is not possible to replicate with user-level Javascript running on the page. You have to use callback functions. And if it were possible, there would already be a ready made solution that you should use.

What I am saying is that the user of your code cannot have this:

var result = customPrompt(...);

Rather they must have something in the lines of this:

customPrompt({
    ...

    ok: function() {
        //when user clicked ok
    },

    cancel: function() {
        //when user clicked cancel
    }

});
//Code continues to run here and doesn't wait for the user to click ok or cancel

Upvotes: 3

Chris Bier
Chris Bier

Reputation: 14447

This is how you can get the user's input into the same function as your modal launcher so you can handle it.

<input type="text" id="user-input" />
<a href="#" onClick="handlePrompt(false)">OK</a>

function handlePrompt(launchModal){
     if(launchModal){
         // Code to Launch Modal
     }else{
         var userInput = $("#user-input").val();
         // Do what you want with the input.
     }
}

Upvotes: 0

Related Questions