본문 바로가기
자바스크립트/기본

자바스크립트 (21) - 투두리스트 기능 구현 1

by monsangter 2022. 11. 14.

1. html 투두 폼 만들기.

 

먼저 todo.js 파일을 만들고

 

html에서 임포트한다.

 

유저가 투두를 입력하면 리스트로 반환 해줄 수 있도록 폼을 만들어줘야한다.

 

 

<form id =“todo-form>

    <input type= “text” placeholder = “write a to do and press enter” required/>

</form>

<form id =“todo-form>

    <input type= “text” placeholder = “write a to do and press enter” required/>

</form>

 

<input> 태그의 required 속성은 폼 데이터가 서버로 제출되기 전 반드시 채워져 있어야 하는 입력 필드를 명시한다.

 

2. html 리스트 만들기.

 

todo-list 라는 id를 가진 unordered list를 만들어준다.

앞으로 리스트를 추가할때는 이 리스트 아래에 자바스크립트를 활용해 추가할 것이다.

 

이제 form과 ul을 html에서 js로 가져가보자.

 

3. html에서 js로 가져오기

const toDoForm = document.querySelector("#todo-form")
const toDoInput = document.querySelector("#todo-form input");
const toDoList = document.querySelector("#todo-list");

form은 기본적으로 submit 이벤트를 가진다. 그리고 이는 새로고침을 하기 때문에

이를 제어할 함수를 만든다.

function handleToDoSubmit(event) {
	event.preventDefault();
    const newTodo = toDoInput.value;
    toDoInput.value = "";
}

toDoForm.addEventListener(“submit”,handleToDoSubmit)

 

input을 입력해도 폼에서 인풋이 남아있는데, 엔터를 누르면 모든 입력값이 사라지게 하고 싶다.

 

const newTodo = toDoInput.value;

toDoInput.value = "";

newtodo변수에 값을 저장하고 todoinput.value는 비우자.

 

 

댓글