모ëŠí í´ëĄ ě˝ëŠ ěě
event.preventDefault()
JavaScript if 꾏돸 ëě HTML ěě
const loginInput = document.querySelector('#login-form input');
const loginButton = document.querySelector('#login-form button');
function onLoginBtnClick() {
const username = loginInput.value;
if (username === '') { // form â input(required ěěą ěśę°)
alert('Please write your name.');
} else if (username.length > 15) { // maxlength="15"
alert('Your name is too long.');
}
console.log(username);
loginInput.value = '';
}
loginButton.addEventListener('click', onLoginBtnClick);
<form id="login-form">
<input required maxlength="15" type="text" placeholder="what is your name?">
<button>Log In</button>
</form>
form í꡸ ěěě submit ě´ë˛¤í¸ę° ë°ěí ëë§ë¤ íě´ě§ę° ěëĄęł 욨ë¨
í´ę˛° ë°Šë˛
event.preventDefault() : í´ëš ě´ë˛¤í¸ę° ë°ě ě ë¸ëźě°ě ě 기본 ëěě 졨ěí´ě¤
function onLoginSubmit(event) {
event.preventDefault();
}
loginForm.addEventListener('submit', onLoginSubmit);
HTML
<h1 id="greeting" class="hidden"></h1> <!-- h1ě 기본ě ěźëĄ ě ëł´ě -->
<form id="login-form">
<input required maxlength="15" type="text" placeholder="what is your name?">
<button>Log In</button>
</form>
CSS
.hidden {
display: none;
}
JavaScript
const loginForm = document.querySelector('#login-form');
const loginInput = document.querySelector('#login-form input');
const greeting = document.querySelector('#greeting');
const HIDDEN_CLASSNAME = 'hidden';
// stringě ě ěĽíë ëłěë ę´ěľě ěźëĄ ë돸ěëĄ í기íë¤
function onLoginSubmit(event) {
loginForm.classList.add(HIDDEN_CLASSNAME); // form í꡸ ě¨ęš
const username = loginInput.value;
greeting.innerText = `Hello ${username}`;
greeting.classList.remove(HIDDEN_CLASSNAME); // h1 í꡸ ëł´ě
}
loginForm.addEventListener('submit', onLoginSubmit);