본문 바로가기

Javascript/Javascript(2024 version)

Javascript(1) - 회원 가입 예제, Javascript 출력 예제 / 기본 문법(변수, 데이터 타입)

728x90
반응형

<목차>

1) 회원 가입 예제

2) Javascript 출력 예제

3) Javascript 기본 문법(변수, 데이터 타입)

 

 

 

 

 

1) 회원 가입 예제

memberJoin.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>회원 가입</title>
    <link rel="stylesheet" href="./CSS_folder/memberJoin.css" />
    <script>
      // window : "BOM"이라 하는 객체
      // onload 이벤트 : 페이지가 로딩되는 시점을 인식하는 이벤트
      window.onload = function () {
        // document가 가지고 있는 element(요소)들 중에서 요소의 id 속성값이 "userid"인 요소(태그)를 찾아서 "userid"라는 변수에 저장시키는 코드
        let userid = document.getElementById("userid"); // getElementById 메서드 사용
        let userpw = document.getElementById("userpw");
        let checkpw = document.getElementById("checkpw");

        // keyup : keyboard를 눌렀다가 떼는 순간 발생하는 이벤트
        userid.addEventListener("keyup", function () {
          if (userid.value.length >= 8) {
            userid.style.backgroundColor = "lightblue";
          } else {
            userid.style.backgroundColor = "lightpink";
          }
        });

        checkpw.addEventListener("keyup", function () {
          if (userpw.value == checkpw.value) {
            checkpw.style.backgroundColor = "lightblue";
          } else {
            checkpw.style.backgroundColor = "lightpink";
          }
        });
      };

      function infoCheck() {
        let userid = document.querySelector("#userid");
        let userpw = document.querySelector("#userpw");
        let checkpw = document.querySelector("#checkpw");

        if (userid.value.length < 8) {
          alert("ID는 8자 이상 쓰세요!");
          return false; // return 값을 false로 반환하면 submit되지 않기 때문에 이렇게 처리함!
        }
        if (
          userpw.value == null ||
          checkpw.value == null ||
          userpw.value == "" ||
          checkpw.value == "" ||
          userpw.value != checkpw.value
        ) {
          alert("PW가 작성되지 않거나 일치하지 않아요!");
          return false;
        }
        return true;
      }
    </script>
  </head>
  <body>
    <div>
      <h1>회원 가입</h1>
    </div>
    <!-- onsubmit="return infoCheck();" => submit할 때 해당 함수를 호출하는 속성 -->
    <!-- onsubmit="return false;"인 경우에는 submit이 되지 않는다!! -->
    <form action="" method="get" onsubmit="return infoCheck();">
      <fieldset>
        <label for="userid">아이디</label>
        <input
          type="text"
          name="userid"
          id="userid"
          class="joinForm"
          placeholder="아이디는 8자 이상"
        />
        <br />
        <label for="userpw">비밀번호</label>
        <input type="password" name="userpw" id="userpw" class="joinForm" />
        <br />
        <label for="checkpw">비밀번호 확인</label>
        <input type="password" id="checkpw" class="joinForm" />
        <br />
        <input type="submit" value="가입" class="inputButton" />
        <input type="reset" value="취소" class="inputButton" />
      </fieldset>
    </form>
  </body>
</html>

 

 

memberJoin.css

body {
  width: 100%;
}

div {
  width: 700px;
  margin: 0 auto;
  text-align: center;
}

form {
  width: 700px;
  margin: 0 auto;
}

fieldset {
  text-align: center;
  font-weight: bold;
}

fieldset > label {
  display: inline-block;
  width: 150px;
  margin-right: 100px;
  font-size: 20px;
}

fieldset > input {
  margin: 40px 0;
}

fieldset > .joinForm {
  width: 250px;
  height: 40px;
}

fieldset > .inputButton {
  width: 100px;
  font-weight: bold;
}

 

 

 

 

 

 

※ 회원 가입 후 쿼리스트링 결과 화면 : form 태그의 method 속성값으로 "get" 지정함!

 

 

 

2) Javascript 출력 예제

00.스크립트.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./js_folder/jsTest.js"></script>
    <script>
      document.write("안녕하세요2222<br>");
    </script>
  </head>
  <body>
    <script>
      document.write("안녕하세요3333<br>");
    </script>
    <h1>자바스크립트</h1>
    <script>
      document.write("안녕하세요4444<br>");
    </script>
    <!-- 
        * 스크립트 코드 작성 영역
        코드가 실행되기 위해서는 <script> 태그 안에 넣어서
        사용하며, <head>에 오던 <body>에 오던 아무데나
        와도 상관이 없고, 여러 번 사용해도 상관없다.
        but 실행되는 순서가 다르다. 
     -->
  </body>
</html>

 

 

jsTest.js

/*
    document.write()은 자바스크립트에서 HTML 문서에
    텍스트를 직접 작성할 때 사용된다.
    HTML을 처리하는 방식으로 문자열을 출력하기 때문에
    문자열 내의 개행 문자(\n)가 HTML에서 개행으로 해석되지 않음!
*/
document.write("안녕하세요1111<br>");

 

 

 

3) Javascript 기본 문법

01.기본문법.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
      // 주석
      /*
            여러 줄 주석
        */

      // 변수
      // var, let, const
      // 자바스크립트는 변수의 데이터 타입이 정해지지 않아도 변수 키워드를 통해 정의할 수 있다!
      var a = 10;
      a = 1.2;
      var a = "안녕"; // var는 두 번 초기화가 가능하다는 에러를 가지고 있어 문제가 된다!
      var b = "Hello";
      let c = 20;
      // let c = 30; --> var의 error를 잡아냄: 동일한 이름의 변수명 재선언 불가
      const d = true;
      // d = false; --> error: const는 상수를 정의하는 변수 키워드로, 값을 재할당할 수 없음!

      console.log(a);
      console.log(b);
      console.log(c);
      console.log(d);

      // 데이터 타입
      /*
            1. Number
            2. String
            3. Undefined
            4. Null
            5. Boolean
            6. Object
      */

      console.log("----숫자----");
      let point = 123;
      console.log(point);
      console.log(typeof point);
      point = -1.23;
      console.log(typeof point);

      // NaN : Not a Number
      point = 1 * "A";
      console.log(point);
      console.log(typeof NaN); // NaN은 "Number 타입"으로 간주함!!
      console.log(typeof point);

      // String : "", '' 사이의 문자
      // ex. "아이디 : 'asdf1234'입니다."

      /*
            undefined : 변수가 선언되었지만 아직 값이
            할당되지 않았을 때의 기본값
      */
      let e;
      console.log(e); // 값이 할당되지 않았을 때의 값을 "undefined"이라 한다!

      /*
            null : '값이 없는 상태'를 의미함
            변수나 객체 속성이 빈 값임을 명시적으로 나타낼 때 사용함
     */
      console.log("----null----");
      f = null;
      console.log(f);
      console.log(typeof f);

      /*
            null vs undefined
            == 연산자 : null과 undefined는 동등 연산자(==)로
            비교할 때 같다고 말할 수 있다.
            두 값이 모두 '비어 있음'을 나타냄
            === 연산자 : 일치 연산자(===)는 값과 타입을
            모두 비교하므로 null과 undefined는 일치하지 않는다.
      */
      console.log(null == undefined); // true
      console.log(null === undefined); // false
      console.log(typeof undefined); // "undefined"
      console.log(typeof null); // "object"
      // "null" 데이터 타입의 경우, 값이 없는 상태이기는 하지만 typeof를 적용했을 때 "Object" 타입이 나올 뿐이라고 이해하면 된다!

      // Boolean : true, false

      // Object : { name : value } 형태
      let book = {
        title: "책",
        point: 123,
      };
      console.log(book);
      console.log(typeof book);
    </script>
  </head>
  <body></body>
</html>