javascript 入力ダイヤログを表示する

javascript 入力ダイヤログを表示する

javascriptで、window.prompt()を使用して、入力ダイヤログを表示するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ firefox97

window.prompt()使い方

window.prompt()を使うと、入力ファーム付きのダイアログを表示することが可能です。

window.prompt("メッセージ","フォームのデフォルトの値")

// windowオブジェクトは省略化
prompt()

window.prompt()使い方

// 入力フォーム表示
let result = prompt("入力フォーム", "foo");

if (result == null) {
  window.alert("キャンセル");
} else {
  window.alert(result + "が入力されました");
}

実行結果(chrome99)

実行結果(firefox97)

サンプルコード

以下は、
「ダイヤログ表示」ボタンをクリックして、入力ダイヤログを表示する
サンプルコードとなります。

※cssには「bootstrap material」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet"
    href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css"
    integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous">
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 25px;
  }
</style>
<script>

  function hoge() {

    let result = prompt("入力フォーム", "foo");

    if (result == null) {
      window.alert("キャンセル");
    } else {
      window.alert(result + "が入力されました");
    }

  }

</script>

<body>
  <div class="main">

    <h2><span id="disp" class="badge badge-primary">hello world</span></h2>

    <button onclick="hoge()" type="button" class="btn btn-raised btn-warning">
      ダイヤログ表示
    </button>

  </div>
</body>

</html>

入力ダイヤログが表示されていることが確認できます。