Home  >  Article  >  Web Front-end  >  How to use javascript to implement prompt box

How to use javascript to implement prompt box

WBOY
WBOYOriginal
2022-04-13 17:03:542642browse

In JavaScript, you can use the prompt() method of the Window object to implement a prompt box. This method can pop up a prompt box with an input box, an "OK" button and a "Cancel" button. The syntax is "prompt("sometext","defaultText")".

How to use javascript to implement prompt box

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

How to use javascript to implement a prompt box

If you want the user to enter a value before entering the page, you will usually use a prompt box.

When the prompt box pops up, the user will have to enter a value and click "OK" or click "Cancel" to continue.

If the user clicks "OK", the box returns the input value. If the user clicks Cancel, this box returns NULL.

The syntax is:

window.prompt("sometext","defaultText");

The window.prompt() method can be written without the window prefix.

The example is as follows:

<html>
<body>
<h1>JavaScript Prompt</h1>
<button onclick="myFunction()">试一试</button>
<p id="demo"></p>
<script>
function myFunction() {
  var txt;
  var person = prompt("请输入您的名字:", "哈利波特");
  if (person == null || person == "") {
    txt = "用户取消输入";
  } else {
    txt = "你好," + person + "!今天过得好吗?";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>

Output result:

How to use javascript to implement prompt box

##After clicking OK, the output result is:

How to use javascript to implement prompt box

【Related recommendations:

javascript video tutorial, web front-end

The above is the detailed content of How to use javascript to implement prompt box. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn