
1. hidden
- 숨기기
- style.css
.hidden{ display: none; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> </head> <body> <form class="login-form hidden" id="login-form"> <input required maxlength="15" type="text" placeholder="What is your name?" /> <!--사용자로부터 값 입력받기--> </form> <a href="https://www.naver.com">Go to Naver</a> <script src="app.js"></script> </body> </html>

2. 값을 입력받은 이후 설정
- input 태그는 사라짐
const loginForm = document.querySelector("#login-form"); const loginInput = document.querySelector("#login-form input"); // input 태그 가져오기 function onLoginSubmit(event) { // 자리만 만들어주면 됨 event.preventDefault(); const username = loginInput.value; // 유저가 입력한 값 가져오기 loginForm.classList.add("hidden"); // 폼 숨기기 console.log(username); // 콘솔에 유저네임 출력 } loginForm.addEventListener("submit",onLoginSubmit);


- input 태그는 사라지고 h1은 표시
- index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> </head> <body> <form class="login-form" id="login-form"> <input required maxlength="15" type="text" placeholder="What is your name?" /> <!--사용자로부터 값 입력받기--> </form> <h1 class="hidden"></h1> <script src="app.js"></script> </body> </html>

- input 태그는 사라지고 h1에 입력받은 값을 표함하여 지정된 텍스트 설정
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> </head> <body> <form class="login-form" id="login-form"> <input required maxlength="15" type="text" placeholder="What is your name?" /> <!--사용자로부터 값 입력받기--> </form> <h1 id="greeting" class="hidden"></h1> <script src="app.js"></script> </body> </html>
- app.js
const loginForm = document.querySelector("#login-form"); const loginInput = document.querySelector("#login-form input"); const freeting =- document.querySelector("#greeting"); function onLoginSubmit(event) { // 자리만 만들어주면 됨 event.preventDefault(); loginForm.classList.add("hidden"); // 폼 숨기기 const username = loginInput.value; // 유저가 입력한 값 가져오기 greeting.innerText = "Hello " + username; } loginForm.addEventListener("submit",onLoginSubmit);


- input 태그는 사라지고 h1에 입력받은 값을 표함하여 지정된 텍스트 표시
const loginForm = document.querySelector("#login-form"); const loginInput = document.querySelector("#login-form input"); const freeting =- document.querySelector("#greeting"); const HIDDEN_CLASSNAME = "hidden"; function onLoginSubmit(event) { event.preventDefault(); // 새로고침 방지 loginForm.classList.add(HIDDEN_CLASSNAME); // 폼 숨기기 const username = loginInput.value; // loginInput에 값을 변수에 저장하기 greeting.innerText = `Hello ${username}`; //저장된 값을 변수 값에 넣기 greeting.classList.remove(HIDDEN_CLASSNAME); // hidden 클래스명 없애기 } loginForm.addEventListener("submit",onLoginSubmit);


Share article