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

JavaScriptでTODOリストを作ってみた part.1

Last updated at Posted at 2024-10-07

こんばんは!gamubaruです!

これから技術のアウトプットとして、記事を公開していこうと思います。
記事の書き方はどんどん修正していけたらと思うので、まずは書くことを目標にしていきます。
どうぞよろしくお願いします。

jsの参考サイトはよく見るが、全くアウトプットすることなく読んだだけ(覚えてない)になっているので、
手始めにタスク管理を作ってみたいと思う。

機能としては下記3つを実装していきたい!
1. タスク追加
2. タスク削除
3. タスク編集(更新)

partなんぼまでなるか分からないけど、最後まで頑張ります。

ファイル構成はindex.htmlとjsフォルダにmain.js

では、スタート!!

1.HTMLに記入欄と送信ボタンを設置

    <section>
        <h1>TODOリスト</h1>
        <div id="id-todoArea">
            <ul id="id-todoList">
            </ul>
        </div>
        <div id="inputArea">
            <label for="id-input">TODOを追加:</label>
            <input type="text" id="id-input">
            <button id="id-add" >追加</button>
        </div>
    </section>

スクリーンショット 2024-10-07 230631.png

2.タスク追加

初めに、id属性が"id-add"となっている要素(追加ボタン)を取得する

  const addBtn = document.getElementById('id-add');

次にaddBtnがクリックされたら動く、という処理を書く


 addBtn.addEventListener('click', (event)=> {
    console.log(`クリックされたよ!!`)
 })

クリックされたら、inputの内容を取得する。このとき内容がない場合は処理終了とする

 addBtn.addEventListener('click', (event)=> {
    const inputTodo = document.getElementById('id-input')
    const todoValue = inputTodo.value;
    if(todoValue === null) return
 })

最後にli要素を作成して、todoListに反映させる

addBtn.addEventListener('click', (event)=> {
    // Todoの内容を取得する。なにもない場合は処理終了
    const inputTodo = document.getElementById('id-input')
    const todoValue = inputTodo.value;
    if(todoValue === null) return
    
    // li要素を作成して、todoListに反映させる
    const todoArea = document.getElementById('id-todoList')
    const liElm = document.createElement('li')
    liElm.textContent = todoValue
    todoArea.appendChild(liElm)
    inputTodo.value = ""
})

こんな具合で書いてみました。
最後にinputエリアはクリアしました

完成した画面はこんな感じ(cssは無視)
スクリーンショット 2024-10-07 233614.png

概ねこんなもんでいいでしょう。。。

次回はタスクを追加したときに、編集ボタンと削除ボタンを追加する実装を書いていこうと思います。

あざした!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?