매진2 2023. 6. 14. 21:40
728x90

https://www.w3schools.com/tags/tag_form.asp

 

HTML form tag

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

먼저 공식문서를 첨부했다.

그리고 내가 이해한 내용을 써보려고한다.

 

사용자가 input 창에서 댓글을 쓰면 포커스가 input 창에 있어서 enter를 눌러도 댓글이 올라가지지 않았다.

포커스가 버튼에 있어야만 enter 눌렀을 때 댓글이 달렸는데.. 그러면 의미가 없지 않은가ㅜㅜ

그래서 input에 포커스가 잡혀있더라도 enter를 누르면 댓글이 달릴 수 있도록 하고 싶었다.

 

그러다 html의 form 태그를 알게되었다.

form 태그는  버튼을 클릭하거나 enter를 눌렀을때 데이터를 전송해주는 태그이다.

 

input과 button 둘다 적용되어야하니까 form 태그로 input과 button 태그를 감싸주었다.

<form class="comment">
  <input id="input" placeholder="댓글 달기..." />
  <button id="button">게시</button>
</form>

그리고 form 태그가 버튼을 클릭하거나 enter를 눌렀을때 데이터를 전송하면서

페이지를 새로 로딩하는 기본값이 있기 때문에

기본값을 방지해주는 e.preventDefault() 메소드를 자바스크립트에 추가해주었다.

 e.preventDefault();
728x90