HTML
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Momentum App</title> </head> <body> <div id="login-form"> <input type="text" placeholder="What is your name?" /> <button>Log In</button> </div> <script src="app.js"> </script> </body> </html> |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Momentum App</title> </head> <body> <form id="login-form"> <input required maxlength="15" type="text" placeholder="What is your name?" /> <button>Log In</button> </form> <script src="app.js"> </script> </body> </html> |
1. JS로 input 창의 username 유효성검사를 할 수 있지만 브라우저 HTML이 제공하는 <form> <input>을 통해 적용시킬 수 있다.
2-1. form의 경우 input 입력하고 엔터 or 버튼클릭하면 자동으로 submit 제출됨 (새로고침) 그렇기 때문에 JS에서 click이 필요없다.
ㄴ 자동으로 submit 되기전 입력값을 저장하는 것이 필요하다.
2-2. form으로 변경한 이유는 ruquired을 활용하기 위해, div로는 적용 불가능
3. input type에는 checkbox, data, email, file, number, password, pickers, radio, search, tel, text, url 있다
브라우저에서 기본적으로 제공하는 것들을 최대한 활용하는 것이 좋다.
JS
| const loginInput = document.querySelector("#login-form input"); const loginButton = document.querySelector("#login-form button"); function onLoginBtnClick() { //username유효성 const username = loginInput.value; if (username === "") { alert("Please write your name!"); } else if (username.length > 15) { alert("Your name is too long."); } else { console.log("hello", userName); } } loginButton.addEventListener("click", onLoginBtnClick); |
const loginForm = document.querySelector("#login-form"); const loginInput = document.querySelector("#login-form input"); function onLoginSubmit(event){ event.preventDefault(); const username = loginInput.value; console.log(username); } loginForm.addEventListener("submit", onLoginSubmit); |
* username 유효성 검사
1. "string" 문자길이 === string.length
2. 입력값이 없을 때 확인하는건 === "" (blank)
3. 브라우저에서 제공하는 것 활용하기 때문에 안써도된다.
* 브라우저의 기본적인 동작을 멈추는 방법
<form>의 경우 엔터 혹은 버튼클릭시 자동으로 submit돼서 새로고침이 된다. 입력된 정보를
가져오기 위해서는 브라우저가 자동으로 작동되는 새로고침을 중단시켜야 하는데 아래와 같은
코드를 사용해서 멈춰줄 수 있다.
function onLoginSubmit(event){
event.preventDefault();
function()을 사용하게 되면 발생하는 event에 정보를 알수 없지만 function(tomato)라는 토마토 그릇을
만들어 주면 event 정보가 토마토 그릇에 저장이 된다. Console.log(toamto)하면 목록 확인가능.
목록 중 preventDefault()를 사용하게되면 브라우저가 자동으로 작동하는 기능을 멈추게함. 맞나?
'프론트엔드 > javascript' 카테고리의 다른 글
| javascript (8) - Login 만들기 #2 (0) | 2023.04.04 |
|---|---|
| javascript (9) - event.preventDefault (0) | 2023.04.04 |
| javascript (7) - Html, CSS, JavaScript, toggle (0) | 2023.04.03 |
| javascript (6) - click event, window event (0) | 2023.04.03 |
| javascript (5) - querySelector (0) | 2023.04.03 |