<div id="login-form">
<input
type="text"
placeholder="What is your name?"
/>
<button>Log In</button>
</div>
input
과 button
을 감싸고 있는 div
를 먼저 불러와 변수에 할당한 후,
해당 변수에 querySelector
를 사용하여 접근한다.
// querySelector를 사용할 경우, class, id, tagname 모두 검색이 가능하므로 대상을 명확히 작성해야 한다.
const loginForm = document.getElementById("login-form")
// document가 아닌 loginForm 안에서 바로 찾을 수 있다.
const loginInput = loginForm.querySelector("input");
const loginButton = loginForm.querySelector("tutton");
document.querySelector
를 사용해
#login-form
의 input
과 button
으로 바로 접근한다.
const loginInput = document.querySelector("#login-form input");
const loginButton = document.querySelector("#login-form button");
<body>
<div id="login-form">
<input
type="text"
placeholder="What is your name?"
/>
<button>Log In</button>
</div>
<script src="app.js"></script>
</body>
function onLoginBtnClick() {
const username = loginInput.value;
if (username === "") {
alert("Please write your name.")
} else if (username.length > 15) {
alert("Your name is too long.")
}
}
loginButton.addEventListener("click", onLoginBtnClick);
❗️ 그러나 HTML에 해당 기능이 있다면 이미 가지고 있는 기능을 사용하는 것이 가장 좋다!
<form id="login-form">
<input
required
maxlength="15"
type="text"
placeholder="What is your name?"
/>
<button>Log In</button>
</form>
input
의 유효성 검사를 작동시키기 위해서는 input
이 form
안에 있어야 한다.
input
안의 button 혹은 엔터키를 누르거나, type
이 submit
인 input
을 클릭하면 form
이 submit 되어 새로고침 된다.
required
: 필수 입력 항목
maxlength
: 최대 글자 수