1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【エラー】TODOリスト追加エラー 素のJavaScriptだけでTODOアプリを作成してみよう

Last updated at Posted at 2025-07-13

エラー内容

入力した値をTODOリストに追加したい!
inputTextを入力していないのに、
TODOリストに"inputText"と入ってしまった!!

簡単な正しい仕様

①入力したい値の入力
②【追加】ボタンを押下
③TODOリストに①で入力した内容が反映される

入力した値 → hoge 
実際にTODOリストに入る値 → hoge

今回のエラーによって起こる挙動

入力した値 → hoge 
実際にTODOリストに入る値 → inputText

◎反映するテキストの値を設定するコード

index.js
const onClickAdd = () => {
  //テキストボックスの値を取得し、初期化する
  const inputText = document.getElementById("add-text").value;
  document.getElementById("add-text").value = "";

  //省略...

  //p生成
  const p = document.createElement("p");
  p.className = "todo-item";
  p.innerText = "inputText"; 

  //imcomplete-listを取得後、li変数をその配下に入れる処理
  document.getElementById("incomplete-list").appendChild(li);
};

◎追加ボタンの内容

index.html
    <div class="input-area">
      <input id="add-text" placeholder="ToDoを入力" />
      <button id="add-button">追加</button>
    </div>

原因

pタグのテキストの値を設定するときに、inputTextの変数を設定したい。
変数なのにinputTextをダブルクォーテーションで囲んでしまった!!
そのため、【追加】ボタンを押すとそのまま「inputText」と反映された!

index.js
   p.innerText = "inputText";  

正しいコード

変数inputTextに囲っていたダブルクォーテーションを外すと、
リストが追加されました!!

index.js
   p.innerText = inputText; 

実行結果

入力した値 → hoge
実際にTODOリストに入る値 → hoge

気を付けること

・とにかく変数は基本、ダブルクォーテーションで囲わないこと!!
・[] 、()、 {} などの使い分けがややこしいため、気を付けること!

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?