Spencer Cornwall
Spencer Cornwall

Reputation: 289

how do I get a function to return the result of an onclick function?

I am trying to understand how to make something like windows.prompt(), as in, you call is as a function and it gives you the result of the button pressed. IE.

var a = customPrompt('message', ['buttonName1','buttonName2']);

I'm looking for a function like:

function customPrompt(message, buttonNames){
    $('body').append($("<div id='Calert'>").append($("<div id='CalertMessage'>").text(message)));
    $('#Calert').append($("<div id='CalertButtons'>"));
    for(var i=0;i<buttonNames.length;i++){
        $('#CalertButtons').append($("<div id='CalertButton'>").text(buttonNames[i]));
    }
    Here, the function needs to return which button was clicked.
}

The main issue I am having is that if I give the buttons an onclick, then it violates scope, and I can't return from my customPrompt function. but I can't exactly make my entire web page wait until a button is pressed.

Upvotes: 2

Views: 140

Answers (1)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

The function should be like this:

function customPrompt(message, buttonNames, callback){
    $('body').append($("<div id='Calert'>").append($("<div id='CalertMessage'>").text(message)));
    $('#Calert').append($("<div id='CalertButtons'>"));
    buttonNames.forEach(function(name, index) {
        var $button = $("<div id='CalertButton'>").text(name).appendTo('#CalertButtons'); // create the button
        $button.on('click', function() {                // when the button is clicked
            // probably destroy the dialog box
            callback(name, index);                      // call the callback passing to it the name and the index of the clicked button
        });
    });
}

and then you can use it like this:

customPrompt("Hello, wolrd!", ["aaa", "bbb"], function(name, index) {
     // if the user clicks the aaa button then: name === 'aaa' and index === 0
     // if the user clicks the bbb button then: name === 'bbb' and index === 1
});

Upvotes: 1

Related Questions