개발/Project(CSS,HTML,JAVASCRIPT-홈페이지)

회원가입 페이지 만들기 - 2 (Javascript)

잇(IT) 2023. 8. 25. 13:26
728x90
- Javascript 코드
function changePhone1(){
    const phone1 = document.getElementById("phone1").value
    if(phone1.length === 3) {
        document.getElementById("phone2").focus()
    }
}

function changePhone2(){
    const phone2 = document.getElementById("phone2").value
    if(phone2.length === 4) {
        document.getElementById("phone3").focus()
    }
}

function changePhone3(){
    const phone1 = document.getElementById("phone1").value
    const phone2 = document.getElementById("phone2").value
    const phone3 = document.getElementById("phone3").value
    if(phone1.length === 3 && phone2.length === 4 && phone3.length === 4){
        document.getElementById("token__button").style = "background-color: #FFFFFF; color: #0068FF; cursor: pointer;"
        document.getElementById("token__button").removeAttribute("disabled")
    }
}

function getToken(){
    const token = String(Math.floor(Math.random() * 1000000)).padStart(6, "0")
    document.getElementById("token").innerText = token

    document.getElementById("token__button").style = "background-color: #FFFFFF; cursor: default;"
    document.getElementById("token__button").setAttribute("disabled", "true")
    document.getElementById("token__timer__confirm__button").style="background-color: #0068FF; color: #FFFFFF; cursor: pointer;"
    document.getElementById("token__timer__confirm__button").removeAttribute("disabled")
    getTokenTimer()
}

let interval;

function getTokenTimer(){
    let timer = 10
    interval = setInterval(() => {
        if(timer >= 0){
            const minutes = Math.floor(timer / 60)
            const seconds = timer % 60

            document.getElementById("token__timer").innerText = minutes + ":" + String(seconds).padStart(2, "0")
            timer -= 1
        } else {
            document.getElementById("token").innerText = "000000"
            document.getElementById("token__button").style = ""
            document.getElementById("token__button").setAttribute("disabled", "true")

            document.getElementById("token__timer").innerText = "3:00"
            document.getElementById("token__timer__confirm__button").style = ""
            document.getElementById("token__timer__confirm__button").setAttribute("disabled", "true")

            clearInterval(interval)
        }
    }, 1000)
}

function getTokenTimerConfirm(){
    clearInterval(interval)
    document.getElementById("token__timer__confirm__button").style = "background-color: #FFFFFF; cursor: default;"
    document.getElementById("token__timer__confirm__button").setAttribute("disabled", "true")
    document.getElementById("token__timer__confirm__button").innerText = "인증완료"
    alert("인증이 완료되었습니다.")

    document.getElementById("signup__button").style = "background-color: #FFFFFF; color: #0068FF; border: 1px solid #0068FF ;cursor: pointer;"
    document.getElementById("signup__button").removeAttribute("disabled")
}

function signup(){
    const email = document.getElementById("email").value
    const writer = document.getElementById("writer").value
    const password1 = document.getElementById("password1").value
    const password2 = document.getElementById("password2").value
    const location = document.getElementById("location").value
    const genderWoman = document.getElementById("gender__woman").checked
    const genderMan = document.getElementById("gender__man").checked

    let isValid = true
    if(email.includes("@") === false) {
        document.getElementById("error__email").innerText = "이메일이 올바르지 않습니다."
        isValid = false
    } else {
        document.getElementById("error__email").innerText = ""
    }

    if(writer === "") {
        document.getElementById("error__writer").innerText = "이름이 올바르지 않습니다."
        isValid = false
    } else {
        document.getElementById("error__writer").innerText = ""
    }

    if(password1 === ""){
        document.getElementById("error__password1").innerText = "비밀번호를 입력해 주세요."
        isValid = false
    } else {
        document.getElementById("error__password1").innerText = ""
    }

    if(password2 === ""){
        document.getElementById("error__password2").innerText = "비밀번호를 입력해 주세요."
        isValid = false
    } else {
        document.getElementById("error__password2").innerText = ""
    }

    if(password1 !== password2) {
        document.getElementById("error__password1").innerText = "비밀번호가 일치하지 않습니다."
        document.getElementById("error__password2").innerText = "비밀번호가 일치하지 않습니다."
        isValid = false
    }

    if(location !== "서울" && location !== "경기" && location !== "인천"){
        document.getElementById("error__location").innerText = "지역을 선택해 주세요."
        isValid = false
    } else {
        document.getElementById("error__location").innerText = ""
    }

    if(genderWoman === false && genderMan === false){
        document.getElementById("error__gender").innerText = "성별을 선택해 주세요."
        isValid = false
    } else {
        document.getElementById("error__gender").innerText = ""
    }

    if(isValid === true){
        alert("가입을 축하합니다.")
    }
}

- html

 <div class="phone__wrapper">
        <input id="phone1" class="phoneNum" type="text" onchange="changePhone1()" onkeyup="onchange()" /> -
        <input id="phone2" class="phoneNum" onchange="changePhone2()" onkeyup="onchange()" /> -
        <input id="phone3" class="phoneNum" onchange="changePhone3()" onkeyup="onchange()" />
    </div>

- 핸드폰 번호 입력 관련 html 코드를 보게 되면 첫번째 각 번호 입력 박스에 onchange가 일어나면 각 함수가 실행되도록 코드가 작성되어 있다.

function changePhone1(){
    const phone1 = document.getElementById("phone1").value
    if(phone1.length === 3) {
        document.getElementById("phone2").focus()
    }
}

function changePhone2(){
    const phone2 = document.getElementById("phone2").value
    if(phone2.length === 4) {
        document.getElementById("phone3").focus()
    }
}

function changePhone3(){
    const phone1 = document.getElementById("phone1").value
    const phone2 = document.getElementById("phone2").value
    const phone3 = document.getElementById("phone3").value
    if(phone1.length === 3 && phone2.length === 4 && phone3.length === 4){
        document.getElementById("token__button").style = "background-color: #FFFFFF; color: #0068FF; cursor: pointer;"
        document.getElementById("token__button").removeAttribute("disabled")
    }
}

- input 태그에 입력된 값을 받아올 때는 .value를 통해 값을 받아온다.

- 첫번째 박스의 글자가 3글자가 되면 .focus() 즉, 커서의 위치가 id="phone2"로 이동하게 된다.

- focus가 두번째 칸으로 이동하게 되면 마찬가지로 글자가 4글자가 되면 id="phone3"으로 이동하게 된다.

- 3번째 박스에선 앞에 두박스를 포함해 3개의 박스에 입력된 값을 전부 변수로 받는다.

- if문을 통해 조건을 만족하게 되면 

<button id="token__button" onclick="getToken()" disabled>인증번호 전송</button>

- 기존에 disabled로 비활성화 해놓은 button을 활성화 시킨다.

document.getElementById("token__button").style = "background-color: #FFFFFF; color: #0068FF; cursor: pointer;"
document.getElementById("token__button").removeAttribute("disabled")

- .style을 통해 해당 버튼에 대한 스타일을 지정한다.

- removeAttribute("disabled")를 통해 button에 적용된 disabled 속성을 없앤다. 즉, 버튼이 활성화 된다.


<div class="token__wrapper">
        <div class="token" id="token">000000</div>
        <button id="token__button" onclick="getToken()" disabled>인증번호 전송</button>
    </div>

    <div class="token__wrapper">
        <div class="token__timer" id="token__timer">3:00</div>
        <button id="token__timer__confirm__button" onclick="getTokenTimerConfirm()" disabled>인증 완료</button>
    </div>
function getToken(){
    const token = String(Math.floor(Math.random() * 1000000)).padStart(6, "0")
    document.getElementById("token").innerText = token

    document.getElementById("token__button").style = "background-color: #FFFFFF; cursor: default;"
    document.getElementById("token__button").setAttribute("disabled", "true")
    document.getElementById("token__timer__confirm__button").style="background-color: #0068FF; color: #FFFFFF; cursor: pointer;"
    document.getElementById("token__timer__confirm__button").removeAttribute("disabled")
    getTokenTimer()
}

let interval;

function getTokenTimer(){
    let timer = 10
    interval = setInterval(() => {
        if(timer >= 0){
            const minutes = Math.floor(timer / 60)
            const seconds = timer % 60

            document.getElementById("token__timer").innerText = minutes + ":" + String(seconds).padStart(2, "0")
            timer -= 1
        } else {
            document.getElementById("token").innerText = "000000"
            document.getElementById("token__button").style = ""
            document.getElementById("token__button").setAttribute("disabled", "true")

            document.getElementById("token__timer").innerText = "3:00"
            document.getElementById("token__timer__confirm__button").style = ""
            document.getElementById("token__timer__confirm__button").setAttribute("disabled", "true")

            clearInterval(interval)
        }
    }, 1000)
}

function getTokenTimerConfirm(){
    clearInterval(interval)
    document.getElementById("token__timer__confirm__button").style = "background-color: #FFFFFF; cursor: default;"
    document.getElementById("token__timer__confirm__button").setAttribute("disabled", "true")
    document.getElementById("token__timer__confirm__button").innerText = "인증완료"
    alert("인증이 완료되었습니다.")

    document.getElementById("signup__button").style = "background-color: #FFFFFF; color: #0068FF; border: 1px solid #0068FF ;cursor: pointer;"
    document.getElementById("signup__button").removeAttribute("disabled")
}

<div class="token__wrapper">
        <div class="token" id="token">000000</div>
        <button id="token__button" onclick="getToken()" disabled>인증번호 전송</button>
    </div>

- 전화번호를 조건에 맞게 정상적으로 입력하게 되면 인증번호 전송 버튼이 활성화 된다.

- 인증번호 전송 버튼을 onclick() 클릭하게 되면 getToken() 함수가 실행된다.

function getToken(){
    const token = String(Math.floor(Math.random() * 1000000)).padStart(6, "0")
    document.getElementById("token").innerText = token

    document.getElementById("token__button").style = "background-color: #FFFFFF; cursor: default;"
    document.getElementById("token__button").setAttribute("disabled", "true")
    document.getElementById("token__timer__confirm__button").style="background-color: #0068FF; color: #FFFFFF; cursor: pointer;"
    document.getElementById("token__timer__confirm__button").removeAttribute("disabled")
    getTokenTimer()
}

- 임의의 6자리 숫자를 생성하는 token 변수를 생성한다.

- 기존의 id가 token인 부분에 위에서 생성한 token 변수(임의로 생성한 6자리)를 넣는다.

- 인증번호를 한 번 전송한 뒤 기존의 인증번호 전송 버튼은 비활성화 한다.

- 인증번호가 전송되고 기존에 비활성되어 있던 인증 완료 버튼을 활성화 시킨다.

- 위의 절차를 모두 마친 뒤, getTokenTimer() 함수를 실행시킨다.

let interval;

function getTokenTimer(){
    let timer = 10
    interval = setInterval(() => {
        if(timer >= 0){
            const minutes = Math.floor(timer / 60)
            const seconds = timer % 60

            document.getElementById("token__timer").innerText = minutes + ":" + String(seconds).padStart(2, "0")
            timer -= 1
        } else {
            document.getElementById("token").innerText = "000000"
            document.getElementById("token__button").style = ""
            document.getElementById("token__button").setAttribute("disabled", "true")

            document.getElementById("token__timer").innerText = "3:00"
            document.getElementById("token__timer__confirm__button").style = ""
            document.getElementById("token__timer__confirm__button").setAttribute("disabled", "true")

            clearInterval(interval)
        }
    }, 1000)

- setInterval() 함수는 javascript에서 사용되는 타이머 함수 중 하나로, 일정한 시간 간격으로 반복적으로 함수를 호출하는 기능을 제공한다.

- timer를 생성하기 위해 원하는 시간만큼 지정한다 위에서는 3분을 지정할 것이기 때문에 180초를 변수에 지정한다.

- 1000ms마다 timer 변수의 값이 0보다 크면 해당 값을 분과 초로 나눠서 minutes, seconds 변수에 넣는다. 변환한 변수의 값을 innerText를 사용하면 화면에 보여준다.

- 만약, timer의 값이 0이상이 아닌 값이 들어가게 될 경우 token을 000000(초기화) 시켜주고, token__button의 style을 전부 없애고, setAttribute를 통해 비활성화를 시킨다.

- 추가로, 타이머의 기본 시간인 3:00을 innerText를 통해 보여주고, 인증 완료 버튼 또한 style을 없애고, 버튼을 비활성화 시킨다.

clearInterval(interval)

- 마지막으로 clearInterval(interval)을 통해 생성한 interval을 중지시킨다.

 

* 테스트를 위해 timer의 시간을 3초로 임의로 변경하였다.


<div class="token__wrapper">
        <div class="token__timer" id="token__timer">3:00</div>
        <button id="token__timer__confirm__button" onclick="getTokenTimerConfirm()" disabled>인증 완료</button>
    </div>

- 주어진 시간 안에 인증을 완료하게 되면 인증 완료 버튼을 누르고 인증을 받는 경우도 존재한다.

function getTokenTimerConfirm(){
    clearInterval(interval)
    document.getElementById("token__timer__confirm__button").style = "background-color: #FFFFFF; cursor: default;"
    document.getElementById("token__timer__confirm__button").setAttribute("disabled", "true")
    document.getElementById("token__timer__confirm__button").innerText = "인증완료"
    alert("인증이 완료되었습니다.")

    document.getElementById("signup__button").style = "background-color: #FFFFFF; color: #0068FF; border: 1px solid #0068FF ;cursor: pointer;"
    document.getElementById("signup__button").removeAttribute("disabled")
}

- 주어진 시간 안에 인증 완료 버튼을 누르게 되면, getTokenTimerConfirm()함수가 호출되게 된다.

- 인증이 완료되었다는 것은 더이상 setInterval()에 작성한 함수가 작동될 필요가 없다는 것이기 때문에 clearInterval()을 통해 Interval을 중지시킨다.

- 인증 버튼이 눌리게 되면 해당 버튼이 비활성화 된다.

- 동시에 인증 완료 버튼을 통해 인증을 완료한 상태이기 때문에 경고창을 통해 인증이 완료되었음을 사용자에게 알려준다.

- 인증이 완료된 경우, 비활성화 되어 있던, id가 signup-button(가입하기 버튼)을 활성화 시켜준다.


<div class="footer">
        <button id="signup__button" onclick="signup()" disabled>가입하기</button>
    </div>

- 가입하기 버튼이 onclick 되면 signup() 메서드가 실행된다.

function signup(){
    const email = document.getElementById("email").value
    const writer = document.getElementById("writer").value
    const password1 = document.getElementById("password1").value
    const password2 = document.getElementById("password2").value
    const location = document.getElementById("location").value
    const genderWoman = document.getElementById("gender__woman").checked
    const genderMan = document.getElementById("gender__man").checked

    let isValid = true
    if(email.includes("@") === false) {
        document.getElementById("error__email").innerText = "이메일이 올바르지 않습니다."
        isValid = false
    } else {
        document.getElementById("error__email").innerText = ""
    }

    if(writer === "") {
        document.getElementById("error__writer").innerText = "이름이 올바르지 않습니다."
        isValid = false
    } else {
        document.getElementById("error__writer").innerText = ""
    }

    if(password1 === ""){
        document.getElementById("error__password1").innerText = "비밀번호를 입력해 주세요."
        isValid = false
    } else {
        document.getElementById("error__password1").innerText = ""
    }

    if(password2 === ""){
        document.getElementById("error__password2").innerText = "비밀번호를 입력해 주세요."
        isValid = false
    } else {
        document.getElementById("error__password2").innerText = ""
    }

    if(password1 !== password2) {
        document.getElementById("error__password1").innerText = "비밀번호가 일치하지 않습니다."
        document.getElementById("error__password2").innerText = "비밀번호가 일치하지 않습니다."
        isValid = false
    }

    if(location !== "서울" && location !== "경기" && location !== "인천"){
        document.getElementById("error__location").innerText = "지역을 선택해 주세요."
        isValid = false
    } else {
        document.getElementById("error__location").innerText = ""
    }

    if(genderWoman === false && genderMan === false){
        document.getElementById("error__gender").innerText = "성별을 선택해 주세요."
        isValid = false
    } else {
        document.getElementById("error__gender").innerText = ""
    }

    if(isValid === true){
        alert("가입을 축하합니다.")
    }
}
const email = document.getElementById("email").value
    const writer = document.getElementById("writer").value
    const password1 = document.getElementById("password1").value
    const password2 = document.getElementById("password2").value
    const location = document.getElementById("location").value
    const genderWoman = document.getElementById("gender__woman").checked
    const genderMan = document.getElementById("gender__man").checked

- 각 id에 해당하는 입력값들을 가져온다. 회원가입에 있어서 입력해야 하는 필수 항목들에 대한 정보를 가져오는 것이다.

let isValid = true

- 모든 데이터가 유효할 때 상태를 확인하기 위한 isValid라는 변수를 하나 지정한다.

if(email.includes("@") === false) {
        document.getElementById("error__email").innerText = "이메일이 올바르지 않습니다."
        isValid = false
    } else {
        document.getElementById("error__email").innerText = ""
    }

    if(writer === "") {
        document.getElementById("error__writer").innerText = "이름이 올바르지 않습니다."
        isValid = false
    } else {
        document.getElementById("error__writer").innerText = ""
    }

    if(password1 === ""){
        document.getElementById("error__password1").innerText = "비밀번호를 입력해 주세요."
        isValid = false
    } else {
        document.getElementById("error__password1").innerText = ""
    }

    if(password2 === ""){
        document.getElementById("error__password2").innerText = "비밀번호를 입력해 주세요."
        isValid = false
    } else {
        document.getElementById("error__password2").innerText = ""
    }

    if(password1 !== password2) {
        document.getElementById("error__password1").innerText = "비밀번호가 일치하지 않습니다."
        document.getElementById("error__password2").innerText = "비밀번호가 일치하지 않습니다."
        isValid = false
    }

    if(location !== "서울" && location !== "경기" && location !== "인천"){
        document.getElementById("error__location").innerText = "지역을 선택해 주세요."
        isValid = false
    } else {
        document.getElementById("error__location").innerText = ""
    }

    if(genderWoman === false && genderMan === false){
        document.getElementById("error__gender").innerText = "성별을 선택해 주세요."
        isValid = false
    } else {
        document.getElementById("error__gender").innerText = ""
    }

- 가장 기본적인 조건들로만 구성하여 코드를 작성하였다. 위와 같이 원하는 조건이 있으면 해당 조건에 맞게 조건식을 작성하고 조건에 만족하지 않은 값들이 존재하면 isValid를 false로 변경한다.

- 추가로 빨간색 글씨로 경고 문자를 사용자에게 보여준다.

if(isValid === true){
        alert("가입을 축하합니다.")
    }

- 하나라도 만족하지 않으면 isValid가 false로 바뀌게되고, 모든 조건에 만족하게 되면 가입을 축하한다는 알림 창이 뜨도록 설정한다.

728x90