简体   繁体   中英

Using Window.prompt() in Javascript

I have the following code:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to demonstrate the prompt box.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var person = prompt("Choose a name\nJohn\nMike\nSteve\nOliver", "John");

    if (person != null) {
        document.getElementById("demo").innerHTML =
        "Hello " + person + "! How are you today?";
    }
}
</script>

</body>
</html>

Where it shows a popup box asking the user to enter a name, and john is the default name.

I want to make it so the user can click one of the names presented in the popup (John,mike,steve,oliver, etc) and that click would then result in the name appearing in the typable field. Is this possible? Would I need a different kind of prompt in Javascript?

I essentially don't want to type in a value, but be able to click it through a list of names, and click okay or cancel accordingly.

So for example, if the user clicks the "Mike" as a link in the popup, it should fill the box at the bottom with the name "Mike", by clicking it instead of having to type it.

Hopefully that makes sense, any help would be much appreciated.

I want to make it so the user can click one of the names presented in the popup (John,mike,steve,oliver, etc) and that click would then result in the name appearing in the typable field. Is this possible?

Not with prompt() . You will need to make your own UI in HTML, with a form that has the layout you want.

Also, an unrelated note... this code is dangerous:

document.getElementById("demo").innerHTML =
    "Hello " + person + "! How are you today?";

When you concatenate text into HTML, you allow people to enter malicious code, or just normal reserved characters that may break your HTML. Make sure you're setting the text instead.

Check Here

I have added a answer on the basis of @brad

function myFunction() {
    var person = prompt("Choose a name\nJohn\nMike\nSteve\nOliver", "John");

    if (person != null) {
     document.getElementById("demo").innerHTML =
    "Hello " + person + "! How are you today?";
    }
}

 function myFunction() { var person = prompt("Choose a name\\nJohn\\nMike\\nSteve\\nOliver", "John"); if (person != null) { document.getElementById("demo").innerHTML = "Hello " + person + "! How are you today?"; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <p>Click the button to demonstrate the prompt box.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM