네이버 클라우드 부트캠프
39일차 [ 제이쿼리 복습 ]
유정♡
2024. 4. 15. 12:20
[ 데이터를 저장하는 방법 ]
1. 변수
let n=2;
2. 배열
let n=[14, 'a', 3.3]
3. 객체
let n={
name:'it,
age:33,
}
[ null과 undefined 차이점 ]
<head>
</head>
<body>
<script>
const a=true;
const b=false;
document.write(a+"<br>");
const c=null; //값이 지정되지 않음 -> 참조하는 값이 없음
document.write(typeof(c)+"<br>");
const d=undefined; //변수 선언 후 값을 할당하지 않은 상태 -> 공간 자체가 없는 상태
document.write(typeof(d)+"<br>");
const e="자바스크립트"; //백틱 표현 방식
document.write(`${e}`);
</script>
</body>
[ 객체 배열 선언 방식 ]
<head>
</head>
<body>
<script>
const user={
name:'kim',
age:20,
man:true,
};
const post={
title:'제목',
content:"내용",
user, //user:user 라는 뜻 //키의 이름과 값에 들어가는 변수이름이 같을 경우 생략 가능
}
user.name==user['name'];
console.log(user.name);
console.log(user['name']);
console.log(user.man);
user.man=false;
console.log(user.man);
console.log(post.user);
const user2={
name:'lee',
}
//user2='hello'; //error
user2.man=false; //hello때문에 error 발생 -> user2를 const로 설정을 했기 때문 !! // 속성은 병경 가능
console.log(user2); //user2 객체에 'lee'+ false 추가되어 잘 출력 됨
delete user2.man;
console.log('man' in user2);
</script>
</body>
[ 객체 배열 안에 함수 선언 ]
<head>
</head>
<body>
<script>
const user={
name:'kim',
age:20,
man:true,
on:function() {
console.log(` ${user.name} 은 개발자이다. `)
}
};
document.write(user.on()); //undefined 출력 됨
user.on(); //콘솔창에 kim 은 개발자이다. 출력됨
</script>
</body>
[ 함수 : 목적있는 작업을 수행하도록 설계된 독립된 모듈, 익명함수 : 함수를 변수처럼 사용하는 익명함수, 화살표 함수 ]
<head>
</head>
<body>
<script>
//함수 : 목적있는 작업을 수행하도록 설계된 독립된 모듈
function cal(a,b) {
return (a+b)*2;
}
let n1=cal(1,2);
let n2=cal(2,3);
document.write(n1+'<br>');
document.write(n2+'<br>');
//익명 함수 : 함수를 변수처럼 사용하는 익명함수
let cal2 = function(a, b) {
return(a+b)*2;
}
document.write(cal2(1,2)+'<br>');
//화살표 함수 : =>
function func(a){
return a+3;
}
let func2 = (a) => {
console.log('hi');
document.write('hello ');
return a+3;
}
document.write(func2(5)+"<br>");
let func3 = a => a+3; //실행문이 하나일 경우 { 중괄호 } 생략 가능 -> 한줄로 작성 가능
let func4 = () => console.log('hi'); //매개변수 없이 사용 가능
let func5 = () => alert('hi');
let func6 =(a,b) => {
let msg=`${a}, ${b}`;
return msg;
};
document.write(func6(3,4)+"<br>");
</script>
</body>
[ 옵셔널 체이닝 ("?.") 리액트에서 주로 나옴, 주어진 값이 존재 하냐 안 하냐에 대한 연산자 ]
<head>
</head>
<body>
<script>
let n={
name:'tom',
dog:{
name:'jack',
},
};
let n2=n.cat?.name; //optional chaining("?.") -> 리액트에서 많이 나옴 , 주어진 값이 존재 하냐 안 하냐에 대한 연산자
console.log(n2); //undefined 출력 됨 (저장공간 자체가 없어서)
</script>
</body>
const getName=(obj) => {
if(!obj?.name)
//옵셔널 체이닝 / obj라는 객체 안에 name이라는 객체 존재하지 않으면 부정연산자 존재하면 obj.name 돌려받음
return null;
return obj.name;
}
let getPhone=(obj) => {
if(!obj?.phone)
return null;
return obj.phone;
}
//내보내는 첫번째 방법) nodule.export
module.exports={getName, getPhone};
//내보내는 두번째 방법) export default
export default {getName, getPhone};
//불러오는 첫번째 방법) require
const {getName, getPhone} = require('./a.js');
//불러오는 두번째 방법) import
import { getName, getPhone } from './a.js';
const user={
name:"Lee",
age:14,
};
const name=getName(user);
const phone=getPhone(user);
console.log(`이름 : ${name} / 번호 : ${phone}`);
[ 이중 중첩 반복문 sort & push ]
<head>
</head>
<body>
<script>
let n=[];
//이중 중첩 반복문
for(let i=0;i<6;i++) {
let lotto=Math.floor(Math.random()*44)+1;
for(let j in n){
if(lotto==n[j]) {
lotto=Math.floor(Math.random()*44)+1;
}
}
n.push(lotto);
}
n.sort(function(a,b){
return a-b; //a부터 b까지
});
document.write(n);
</script>
</body>
[ promise 동기 & 비동기 ]
Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타낸다.
비동기란? 둘 이상의 객체 또는 이벤트가 동시에 존재하지 않거나 발생하지 않는 경우
(또는 이전 객체 또는 이벤트가 완료될 때까지 기다리지 않고 발생하는 여러 관련 작업)를 말한다.
Promise - JavaScript | MDN (mozilla.org)
Promise - JavaScript | MDN
Promise 객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.
developer.mozilla.org
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.ac{
background-color: aqua;
}
</style>
<script>
function on(){
$("#aa").addClass("ac"); //ac라는 클래스 추가
}
function on1(){
$("#aa").removeClass("ac");
}
function on2(){
$("#aa").toggleClass("ac");
}
</script>
</head>
<body>
<h1 id="aa">h1태그</h1>
<button onclick="on()">CSS추가</button>
<button onclick="on1()">CSS제거</button>
<button onclick="on2()">CSS전환</button>
<script>
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<!-- jQuery CDN -->
<style>
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.modal-frame { text-align: center; }
.modal-wrapper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.2);
opacity: 0; /*display: none;*/
visibility: hidden;
transition: 0.35s;
}
.modal {
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -70%);
box-shadow: 0 0 1.5em hsla(0, 0%, 0%, 0.35);
padding: 20px;
transition: 0.35s;
}
.modal-header { border-bottom: 1px solid #ddd; }
.modal-header h2 { margin-top: 0; }
.close-modal { float: right; }
.modal-wrapper.act{
opacity: 1;
visibility: visible;
}
.modal-wrapper.act .modal{
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="modal-frame">
<h2>Modal</h2>
<button class="open-modal">Open Modal</button>
</div>
<div class="modal-wrapper">
<div class="modal">
<div class="modal-header">
<h2 class="modal-heading">modal</h2>
</div>
<div class="modal-content">
<p>
안녕하세요 홍길동입니다
</p>
<button class="close-modal">Close</button>
</div>
</div>
</div>
<script>
$('.open-modal').click(function(){
$('.modal-wrapper').addClass('act');
});
$('.close-modal').click(function(){
$('.modal-wrapper').removeClass('act');
})
</script>
</body>
</html>
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<style>
</style>
<script>
let n="hidden";
function ch(){
if(n=="hidden"){
n="visible";
}
else{
n="hidden";
}
let v=document.querySelectorAll('span'); //배열
for(let i of v){
i.style.visibility=n;
}
}
</script>
</head>
<body>
<button type="button" onclick="ch()">button</button>
<hr>
<ul>
<li>I (<span>love</span>) you.</li>
<li>공부(<span>필수</span>)</li>
</ul>
<script>
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<!-- jQuery CDN -->
<style>
</style>
<script>
function on() {
let n=$("#a1").val();
alert(n);
}
function on2() {
$("#a1").val('길동');
}
</script>
</head>
<body>
<input type="text" id="a1">
<button onclick="on()">value가져오기</button>
<button onclick="on2()">value세팅</button>
</body>
</html>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<!-- jQuery CDN -->
</head>
<body>
<div id="content">
<span>Hello~</span>
</div>
<input type="text" id="userId" value="Hello~">
<script>
var print = $('#userId').val();
alert(print);
</script>
</body>
</html>
<style>
body {
margin: 0;
height: 2000px;
}
header {
display: flex;
justify-content: center;
padding: 20px;
width: 100%;
background-color: #eee;
}
.header-inner {
width: 80%;
display: flex;
justify-content: space-between;
}
.gnb a {
text-transform: capitalize;
}
.top-banner {
height: 300px;
background-color: pink;
font-size: 1.5em;
display: flex;
justify-content: center;
align-items: center;
}
header.act{
position: fixed;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="container">
<div class="top-banner" role="banner">Content</div>
<header>
<div class="header-inner">
<div class="logo">jquery</div>
<div class="gnb" role="navigation">
<a href="#none">home</a>
<a href="#none">company</a>
<a href="#none">product</a>
<a href="#none">contact</a>
</div>
</div>
</header>
</div>
<script>
let n=$('header').offset().top; //300
$(window).scroll(function(){
if($(this).scrollTop() > n){
$('header').addClass("act");
}
else{
$('header').removeClass('act');
}
})
</script>
<head>
<style>
a { text-decoration: none; color: #000; }
body {
margin: 0;
height: 150vh;;
}
header {
display: flex;
justify-content: center;
padding: 20px;
position: fixed;
width: 100%;
background-color: #eee;
transition: 0.5s;
}
.header-inner {
width: 80%;
display: flex;
justify-content: space-between;
}
.gnb a {
text-transform: capitalize;
}
.btn-top {
width: 40px;
height: 40px;
position: fixed;
font-size: 2em;
color: #fff !important;
right: 20px;
bottom: -50px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 5px;
text-align: center;
line-height: 45px;
transition: 0.5s;
}
header.active {
background-color: #fff;
box-shadow: 0 3px 5px rgba(0, 0, 0, 0.05);
}
.btn-top.active {
bottom: 20px;
}
</style>
</head>
<body>
<header>
<div class="header-inner">
<div class="logo">Jquery</div>
<div class="gnb">
<a href="#none">home</a>
<a href="#none">company</a>
<a href="#none">product</a>
<a href="#none">contact</a>
</div>
</div>
</header>
<a class="btn-top" href="#">
<i class="bi bi-arrow-up-short"></i>
</a>
<script>
$(window).scroll(function() {
if($(window).scrollTop() > 50) {
$('header, .btn-top').addClass('active');
}
else{
$('header, .btn-top').removeClass('active');
}
})
</script>
</body>
<head>
</head>
<body>
<h1 class="test1">요소 복사</h1>
<span class="test2">요소 감싸기</span>
<span class="test3">요소 모두 한번에 감싸기</span>
<span class="test3">요소 모두 한번에 감싸기</span>
<span class="test3">요소 모두 한번에 감싸기</span>
<div class="test4">안녕</div>
<h1 class="heading">This is H1</h1>
<script>
$('.test1').clone().insertAfter('.test1'); //요소 복사 / 똑같이 복사하여(=clone) 뒤에 삽입(=insertAfter)
$('.test2').wrap('<div class="di"></div>') //요소 감싸기
$('.test3').wrapAll('<p></p>'); //모든요소 감싸기
$('.test4').wrapInner('<p></p>'); //하위요소 감싸기
$('.heading').replaceWith('<h1>제이쿼리</h1>'); //요소 바꾸기
</script>
</body>
<!DOCTYPE html>
<head>
<script>
//textarea에 값을 입력하고 출력버튼을 누르면 내가 쓴 값이 새 창에 뜬다
let win=null;
function on() {
win=window.open("","a","width=300, height=200");
let n=document.getElementById('t');
win.document.open();
win.document.write(n.value); //새창에 내가 쓴 출력 값
win.document.close();
}
</script>
</head>
<body>
<textarea id="t" rows="10" cols="50"></textarea>
<button onclick="on()">출력</button>
</body>
</html>
<!DOCTYPE html>
<head>
</head>
<body onload="on()"> <!--addEventListener-->
<p id="p">마우스 올려봐</p> <!-- 마우스 올리면 violet색으로 변경 mouseover-->
<!-- 마우스 벗어나면 white색으로 변경 mouseout-->
<script>
let n;
function on() {
n=document.getElementById('p');
//함수명을 주는 콜백함수
n.addEventListener('mouseover', fun);
n.addEventListener('mouseout', fun2);
}
function fun() {
n.style.backgroundColor='violet';
}
function fun2() {
n.style.backgroundColor='yellow';
}
</script>
</body>
</html>
<!DOCTYPE html>
<head>
<script>
function on() {
let n=confirm('네이버로 이동할거야?');
return n; //취소: false / 확인: true
}
function no(e) {
e.preventDefault(); //이벤트 디폴트 행동 강제 취소 -> 따아는 클릭이 안 됨 !!
}
</script>
</head>
<body>
<form>
<input type="checkbox">아아<br>
<input type="checkbox" onclick="no(event)">따아(no check)
</form>
</body>
</html>
<!DOCTYPE html>
<head>
<script>
function ch(obj) {
if(obj.value=="") {
alert('이름 입력해야해 !!!');
obj.focus();
}
}
</script>
</head>
<body onload="document.getElementById('name').focus()"> <!-- 이름에 포커스 설장-->
<form>
이름 <input type="text" id="name" onblur="ch(this)"> <!-- 포커스 벗어나면 ch 함수 실행 -->
<p>
학번 <input type="text">
</p>
</form>
</body>
</html>
<!DOCTYPE html>
<head>
<script>
function load(url) {
window.open(url, 'aa');
}
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: pink;
}
.stop {
text-align: center;
font-size: 2rem;
border: 5px solid #333;
border-radius: 10px;
padding: 50px;
box-shadow: 0 0 10px #333;
background-color: blanchedalmond;
}
.buttons button {
padding: 10px 20px;
margin: 0 10px 10px 10px;
font-size: 1.2rem;
border-radius: 5px;
background-color: skyblue;
color: white;
cursor: pointer;
}
.buttons button:hover {
background-color: #333;
color: #f1f1f1;
}
.buttons button span {
display: block;
font-weight: bold;
}
#millisecond {
font-size: 2rem;
}
</style>
</head>
<body>
<div class="stop">
<h1>STOP WATCH</h1>
<h1 class="dis">
<span id="hours" data-alt="hour">00</span>:<span id="minutes" data-alt="min">00</span>:<span
id="seconds" data-alt="sec">00</span>.<span id="millisecond" data-alt="millis">00</span>
</h1>
<div class="buttons">
<button id="btnStart"><span>start</span></button>
<button id="btnPause"><span>pause</span></button>
<button id="btnReset"><span>reset</span></button>
</div>
</div>
<script>
let hours = document.getElementById("hours");
let minutes = document.getElementById("minutes");
let seconds = document.getElementById("seconds");
let millisecond = document.getElementById("millisecond");
let btnStart = document.getElementById("btnStart");
let btnPause = document.getElementById("btnPause");
let btnReset = document.getElementById("btnReset");
let intervalId = null;
let elapsedTime = 0;
btnStart.addEventListener("click", function () {
if (intervalId) {
return;
}
intervalId = setInterval(function () {
elapsedTime += 10;
let totalSeconds = Math.floor(elapsedTime / 1000);
let hoursValue = Math.floor(totalSeconds / 3600);
let minutesValue = Math.floor((totalSeconds % 3600) / 60);
let secondsValue = totalSeconds % 60;
let millisecondValue = Math.floor((elapsedTime % 1000) / 10);
hours.textContent = padZero(hoursValue);
minutes.textContent = padZero(minutesValue);
seconds.textContent = padZero(secondsValue);
millisecond.textContent = padZero(millisecondValue);
if (secondsValue >= 55) {
let colorIntensity = (secondsValue - 54) * 50;
hours.style.color = `rgb(${colorIntensity}, 0, 0)`;
minutes.style.color = `rgb(${colorIntensity}, 0, 0)`;
seconds.style.color = `rgb(${colorIntensity}, 0, 0)`;
millisecond.style.color = `rgb(${colorIntensity}, 0, 0)`;
} else {
hours.style.color = "black";
minutes.style.color = "black";
seconds.style.color = "black";
millisecond.style.color = "black";
}
}, 10);
});
btnPause.addEventListener("click", function () {
clearInterval(intervalId);
intervalId = null;
});
btnReset.addEventListener("click", function () {
clearInterval(intervalId);
intervalId = null;
elapsedTime = 0;
hours.textContent = "00";
minutes.textContent = "00";
seconds.textContent = "00";
millisecond.textContent = "00";
});
function padZero(number) {
return number < 10 ? "0" + number : number;
}
</script>
</body>
</html>
<HTML>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css" />
<link rel="stylesheet" href="test1.css" />
<script src="test1.js"></script>
<style>
div {
padding: 20px;
}
.btn {
position: fixed;
right: 10px;
}
.small {
font-size: small;
border: none;
padding: 5px 7px;
}
.medium {
font-size: medium;
border: none;
padding: 5px 7px;
}
.large {
font-size: large;
border: none;
padding: 5px 7px;
}
.selected {
background-color: black;
color: white;
}
.centerLine {
border: 1px dashed lightgray;
}
.innerLine {
width: 100px;
height: 5px;
margin-left: 0;
background-color: palevioletred;
border: none;
}
</style>
</head>
<body>
<div class="btn">
<button class="small selected" onclick="small()">가</button>
<button class="medium" onclick="medium()">가</button>
<button class="large" onclick="large()">가</button>
</div>
<div class="content">
<h3>웹 개발자의 분류</h3>
<hr class="innerLine" />
<p>
웹퍼블리셔(ui개발자), 개발자(서버개발자): HTML 중심이거나, 서버사이드가
감싸는 웹 구조의 형태를 지향하는 업무 스타일의 직군으로서 웹퍼블리셔는
사용자에게 보여지는 인터페이스 영역을 작업하고, 개발자는 데이터의
비지니스 로직을 전반으로 담당한다. 웹퍼블리셔는 해외에서는 UI개발자로
불린다.
</p>
<p>
프론트엔드, 백엔드 개발자: 프론트엔드 개발자는 백엔드 API에서 가져온
데이터의 출력, 입력을 통한 비지니스 로직 구성과 사용자와 대화하는 사용자
인터페이스 부분을 작업하는 개발자를 말한다. 분별하기 헷갈리는 직종으로
웹퍼블리셔가 있는데, 웹퍼블리셔는 html 중심이거나, 서버사이드가 감싸는
구조 형태의 웹을 지향하는 웹퍼블리셔와 개발자의 업무 스타일의 직군으로서
웹표준 반응형웹과 UI를 만드는 디자인 쪽에 가깝고, 클라이언드 사이드
영역이기도 하지만, 프론트 엔드 개발자는 프론트엔드, 백엔드의 완전한 분리
구조를 지향하는 업무스타일의 직군으로서 웹퍼블리셔와 같이 인터페이스의
디자인 관점도 있지만, 웹퍼블리셔와 달리 컴포넌트 아키텍쳐를 지향하며,
이벤트나 서버와 API 통신해서 로직을 어떻게 푸는 관점을 중시한다. 백엔드
개발자도 기존 개발자와 스펙이 조금 다르고, 백엔드의 뷰는 화면개발이 아닌
API 개발이고, 백엔드 인증 처리도 따로 알아야 하며, 데이터베이스 분석과
API서버를 개발한다. 프론트엔드에서 전달된 데이터의 포맷이나 데이터베이스
입출력 및 다양한 비즈니스 프로세스를 프로그래밍 코드로 구현하는 역할을
한다. 데이터베이스, 웹서버, 네트워킹 등 웹 서버의 인프라에 대한 이해가
필요하다. 웹퍼블리셔와 개발자로 나뉜 방식은 모든 호출을 서버에서
가져와야 했고, 컴포넌트화가 안되었지만, 프론트엔드와 백엔드로 나뉜
개발방식은 서버의 컴퓨터와 사용자 컴퓨터가 http통신으로 데이터만
교환하고 완전히 분리구조를 지향한다.
</p>
<hr class="centerLine" />
<h3>웹 개발자들이 주로 작업하는 환경 운영 체제:</h3>
<hr class="innerLine" />
<ul>
<li>
윈도, 유닉스, 리눅스 클라이언트 측면 언어: HTML, CSS, Javascript, XML ,XHTML
</li>
<li>
클라이언트 측면 js 프레임워크: jQuery, dojo , prototype, YUI, Jindo
</li>
<li>
클라이언트 측면 ui 프레임워크: jQuery UI, fontawesome, bootstrap
</li>
<li>
서버 측면 언어 : JAVA, Node.js, C#(ASP.NET), PHP, JSP, VB
스크립트(ASP), Python 펄, Ruby on Rails, grail 프레임워크 : J2EE,
ASP.NET MVC, ASP.NET Webform, Struts, Spring, ibatis , hibernate , gwt,spring roo, sitemesh , oscache, tiles
</li>
<li>
데이터베이스 : Oracle, MS SQL, Mysql, Postgres 버전 관리 : WinCVS,
TotoiseCVS, Subversion, Rational ClearCase, git
</li>
<li>
웹 서버 : Nginx, Apache, Tomcat, JBoss, WAS, Bea Logic, IIS , jetty
</li>
<li>
도구 : 이클립스, WASD, Editplus, Oracle Developer, 메모장, Notepad++,
Putty, FTP 클라이언트, Zend Studio, Brackets, 비주얼 스튜디오
</li>
</ul>
</div>
<script>
function small() {
$(".content").css("font-size", "1em");
$(".btn").find("button").removeClass("selected");
$(".small").addClass("selected");
}
function medium() {
$(".content").css("font-size", "1.3em");
$(".btn").find("button").removeClass("selected");
$(".medium").addClass("selected");
}
function large() {
$(".content").css("font-size", "2em");
$(".btn").find("button").removeClass("selected");
$(".large").addClass("selected");
}
</script>
</body>
</html>
[ 회원가입 ]
<!DOCTYPE html>
<html>
<head>
<style>
label {
display: inline-block;
width: 160px;
text-align: left;
}
.yn {
width: auto;
}
.star {
font-size: large;
text-align: right;
font-weight: bold;
color: red;
}
#btns {
text-align: center;
}
</style>
</head>
<body>
<form action="Member" method="POST" name="f" onsubmit="return validate()">
<div class="block">
<label for="name">이름 </label><span class="star">*</span> <input type="text" name="name" id="name" required><br>
</div>
<div class="block">
<label for="regnum">주민등록번호 </label><span class="star">*</span> <input type="number" name="regnum" id="regnum" required> - <input type="number" name="regnum2" required><br>
</div>
<div class="block">
<label for="id">아이디 </label><span class="star">*</span> <input type="text" name="id" id="id" required><br>
</div>
<div class="block">
<label for="pwd">비밀번호 </label><span class="star">*</span> <input type="password" name="pwd" id="pwd" required><br>
</div>
<div class="block">
<label for="pwdconfirm">비밀번호 확인 </label><span class="star">*</span> <input type="password" name="pwdconfirm" id="pwdconfirm"><br>
</div>
<div class="block">
<label for="email">이메일</label> <input type="text" name="email" id="email"> @ <input type="text" name="email2" id="email2" value="gmail.com">
<select id="emailselect">
<option value="gmail.com" selected>gmail.com</option>
<option value="nate.com">nate.com</option>
<option value="yahoo.com">yahoo.com</option>
</select>
<br>
</div>
<div class="block">
<label for="mailnum">우편번호</label> <input type="text" name="mailnum" id="mailnum"><br>
</div>
<div class="block">
<label for="addr1">주소</label> <input type="text" name="addr1" id="add1"> <input type="text" name="addr2"><br>
</div>
<div class="block">
<label for="tel">핸드폰 번호</label> <input type="text" name="tel" id="tel"><br>
</div>
<div class="block">
<label for="job">직업</label> <select name="job" size="3" id="job">
<option value="student">학생</option>
<option value="comp">컴퓨터/인터넷</option>
<option value="news">언론</option>
</select><br>
</div>
<label>메일/SMS 정보 수신</label> <input type="radio" name="allowMail" id="yes" value="yes" checked><label for="yes" class="yn">수신</label>
<input type="radio" name="allowMail" id="no" value="no"><label for="no" class="yn">수신거부</label><br>
<div id="btns"><input type="submit" value="회원가입"> <input type="reset" value="취소"></div>
</form>
<script>
const emailselect = document.getElementById("emailselect");
emailselect.addEventListener('change',(event) => {
var email2 = document.getElementById("email2");
email2.value = event.target.value;
});
function isEmpty(str) {
return (!str || str.length === 0);
}
function validate() {
// Checking required
var required = [];
required[0] = document.f.name.value;
required[1] = document.f.regnum.value;
required[2] = document.f.id.value;
required[3] = document.f.pwd.value;
required[4] = document.f.pwdconfirm.value;
required[5] = document.f.regnum2.value;
for (var i = 0; i < required.length; i++) {
if (isEmpty(required[i])) {
alert("값이 비어있습니다.");
return false;
}
}
// pw check
if (!(required[3] === required[4])) {
alert("비밀번호가 같지 않습니다.");
return false;
}
// id check
if (required[2].length < 4) {
alert("아이디는 4글자 이상이어야 합니다.");
return false;
}
// 우편번호 check
var mailnum = document.f.mailnum.value;
if (!mailnum.includes("-")) {
alert("우편번호에는 - 가 들어가야합니다.");
return false;
}
return true;
}
</script>
</body>
</html>
728x90