LoginSignup
0
0

form送信時に値をコンソールに表示できない

Posted at

vscodeのLive Serverを使い、ブラウザを立ち上げる。
フォーム内容を入力し、コンソールに値を表示させたかったが表示されない。(検証ツールにて)
htmlファイルは以下

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Todo</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
  <div class="todo-app">
    <h1>Todoリスト</h1>
    <form id="post-form">
      <input type="text" id="todo-input" placeholder="新しいタスクを入力" />
      <button type="submit" id="add-button">タスクを追加する</button>
    </form>
    <ul id="todo-list">
      <!-- タスクはここに追加される。 -->
    </ul>
  </div>
  <script src="todo.js"></script>
</body>
</html>

値が取得されているかの確認

console.log()では表示されなかったのでalert()で表示させてみたら成功。

原因

フォーム送信時にページがリロードされていることでconsole画面に値が表示されなかった。

対策

event.preventDefault();を関数内に書くことでイベントのデフォルトの処理を防ぐ(今回はフォームの送信ボタンをクリックしたときに、ブラウザがフォームを送信してページをリロードするのがデフォルトの処理)

function addTodo(event) {
  event.preventDefault();
  //処理内容
}
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0