oerkero oerkero - 1 month ago 6
Javascript Question

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.

Answer

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.

Comments