<div id="login-form">
<input type="text" placeholder="What is your name?">
<button>Log In</button>
</div>
input이랑 button을 끌어오고 싶음
const loginForm = document.getElementById("login-form");
const loginInput = loginForm.querySelector("input");
const loginButton = loginForm.querySelector("button");
button을 누르면 console.log에 쓴 것을 기록해 줌
function onLoginBtnClick(){
console.log(loginInput.value);
}
loginButton.addEventListner("click",onLoginBtnClick);
input란에 이름이 들어가는지 최대 길이가 몇인지 등을 지정해주어야함
필수는 아니지만 유효성 검사를 하는 것이 중요함!
-> 유효성 검사를 위해선 form 안에 input이 있어야함
-> but, 이렇게 하면 새로고침이 됨!(form에 있으면 button을 누르면 자동으로 submit이 되기 때문) -> 수정 필요!
html 코드를 변경함!
<form id="login-form">
<input type="text" placeholder="What is your name?" required maxlength="15">
<button>Log In</button>
</form>
_** .preventDefault() **_
// app.js
const HIDDEN_CLASSNAME = "hidden";
function onLogInSubmit(event){ // submit을 할 때 새로고침을 하지 않게 해줌 / 기본적으로 event argument를 사용
event.preventDefault(); // 기본 동작을 하지 못하게 함
}
// style.css
.hidden{
display: none;
}
또 다른 예제 : 링크를 클릭했을 때 페이지가 뜨지 않게 함
// index.html
<a href="naver.com">NAVER</a>
const link = document.querySelector("a");
function handelLinkClick(event){
event.preventDefault();
// alert("clicked!"); // <- 실행 후 페이지가 나타남
}
link.addEventListener("click",handelLinkClick);