JavaScript 독학1
출력문
출력명령문
document.write("내용")
따옴표 표현하기
- document.write("\"");
문자열 연결 +
- <script>
- document.write("Mickey"+"Mouse");
- </script>
숫자를 문자화
<script>
document.write("6+6은 ? " + (6+6));
12
document.write("6+6은 ? " + ('6'+'6'));
66
</script>
alert
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>자바스크립트</title>
<script>
alert('5*6='+5*6);
</script>
</head>
<body>
</body>
</html>
변수
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>자바스크립트</title>
<script>
num = 30;
str = "hi.";
document.write(num);
document.write("<br />");
document.write(str);
</script>
</head>
<body>
</body>
</html>
변수 선언 법칙
변수명에는 영문 숫자 _
대문자,소문자 구별
첫 문자는 숫자가 올수 X
예약어 사용X
예약어의 종류
abstract | case | continue | extends | for |
import | long | private | static | throw |
var | boolean | catch | default | false |
function | in | native | protected | super |
throw | void | break | char | do |
final | goto | instanceof | new | public |
switch | transient | while | byte | class |
double | finally | if | int | null |
return | synchronized | true | with | case |
const | else | float | implements | interface |
package | short | this | try |
상수
const 상수명 = 값;
한번 값을 대입하면 다른 값 대입 X
데이터 형
따옴표
- '\''
- "\""
- "'"
- '"'
배열
- 변수명 = new Array();
- 변수명 = [값,값,값,값];
- document.write(변수명[0]);
boolean
- var bool = true;
- document.write(bool);
- document.write('<br>');
- bool = false;
- document.write(bool);
배열 값 추가하기
배열의 가장 뒤에 값 추가
배열변수명.push(추가할 값);
배열 앞에 값 추가
배열변수명.unshift(추가할 값);
배열의 수(길이) 알아보기
배열변수.length
데이터형 확인하기 typeof
typeof(변수 또는 상수)
형변환 - 데이터를 숫자로 변환하기 parseInt
parseInt(변수)
var str ="String"
str = parseInt(str)
=> NaN(Not a Number)
var str ="55"
str = parseInt(str)
=> 55 (문자열 -> 숫자)
var str ="숫자55"
str = parseInt(str)
=> NaN (숫자로 변환X)
var str ="55숫자"
str = parseInt(str)
=> 55(문자열 -> 숫자)
형변환 - 데이터를 숫자로 변환하기 Number
- Number(변수)
숫자로 시작하더라도 문자열이 들어가있다면 NaN로 값 변경
형변환 - 데이터를 숫자로 변환하기 String
- String(변수)
숫자 -> 문자열
형변환 - 데이터를 논리형으로 변환하기 Boolean
var num = 55
Boolean(str) = true
var str = "55"
Boolean(str) = true
var num = 0
Boolean(str) = false
var str = "false"
Boolean(str) = true
날짜값 가져오기 date
현재의 날짜 데이터를 가져오는 방법
new Date()
const NOW_DATE = new Date();
년도값 가져오기
const NOW_DATE = new Date();
document.write(NOW_DATE.getFullYear());
현재 월 값 가져오기
- const NOW_DATE = new Date();
- document.write(NOW_DATE.getMonth());
월은 0부터 반환하므로 +1를 해준다.
- const NOW_DATE = new Date();
- const NOW_MONTH = NOW_DATE.getMonth() + 1;
- document.write(NOW_MONTH);
현재 일 값 가져오기
- const NOW_DATE = new Date();
- document.write(NOW_DATE.getDate());
현재 요일 값 가져오기
- const NOW_DATE = new Date();
- document.write(NOW_DATE.getDay());
일요일 0 월요일 1 화요일 2 수요일 3 목요일 4 금요일 5 토요일 6
- <script>
- const NOW_DATE = new Date();
- var nowDay = "";
- switch(NOW_DATE.getDay()){
- case 0:
- nowDay = "일요일";
- break;
- case 1:
- nowDay = "월요일";
- break;
- case 2:
- nowDay = "화요일";
- break;
- case 3:
- nowDay = "수요일";
- break;
- case 4:
- nowDay = "목요일";
- break;
- case 5:
- nowDay = "금요일";
- break;
- case 6:
- nowDay = "토요일";
- break;
- default :
- nowDay = "알수없는요일";
- break;
- }
- document.write("오늘은 " + nowDay);
- </script>
현재 시 값 가져오기
- const NOW_DATE = new Date();
- document.write(NOW_DATE.getHours());
현재 분 값 가져오기
- const NOW_DATE = new Date();
- document.write(NOW_DATE.getMinutes());
현재 초 값 가져오기
- const NOW_DATE = new Date();
- document.write(NOW_DATE.getSeconds());
현재 밀리초 값 가져오기
- const NOW_DATE = new Date();
- document.write(NOW_DATE.getMilliseconds());
글로벌 변수와 로컬 변수
글로벌 변수 : 전역 변수
로컬 변수 : 지역 변수
- <script>
- function hello(){
- document.write("Hello world");
- }
- hello();
- </script>
- <script type="text/javascript">
- glo_var = 10;
- function hello(){
- local_var = 20;
- }
- document.write(glo_var);
- //document.write(loaca_var); 출력 안됨
- </script>
로컬 변수 앞에 var가 있으면 함수 안에서만 작동
로컬 변수 앞에 var가 없으면 해당 함수가 한번 호출하고 글로벌 변수가 된다.
- <script type="text/javascript">
- glo_var = 10;
- function hello(){
- var local_var = 20;
- local_var2 = 30;
- }
- hello(); //해당 함수 호출
- document.write(local_var2); //전역 변수가 된다.
- </script>
연산자
== 은 값이 같다면 참이지만 ===은 값과 타입까지 같아야 참
!= 은 값이 다르면 참이지만 !==은 타입도 다르고 값도 달라야 참
if문
if else if else
삼항연산자
- <script>
- document.write(( 1 == 1) ? "true" : "false");
- </script>
switch
- switch (변수명){
- case 값A :
- 값이 A일 때 실행할 명령문;
- break;
- case 값B :
- 값이 B일 때 실행할 명령문;
- break;
- case 값C :
- 값이 C일 때 실행할 명령문;
- break;
- case 값D :
- 값이 D일 때 실행할 명령문;
- break;
- case 값E :
- 값이 E일 때 실행할 명령문;
- break;
- default :
- 위의 값 A ~ E 모두 아닐때 실행할 명령문;
- }
while
- while(조건){
- 조건에 만족할 동안 실행할 명령문
- }
do{
조건식이 참이면 실행할 명령은 여기에 적습니다.
}
while(여기에는 조건식을 적습니다.)
일단 한번 실행을 한후 조건문 검사후 참이면 실행 아니면 빠져나옴
for
- for(변수 선언 초기값 설정;조건식;증감식){
- 조건이 참인 동안 실행할 명령문;
- }
이중for문
- for(변수 선언 및 초기값 설정; 조건식; 증감식){
- for(변수 선언 및 초기값 설정; 조건식; 증감식){
- }
- }
continue문과 break문
continue문 만나면 해야할 명령문 실행하지 않고 그다음 명령문을 실행
break문 만나면 바로 빠져나가는 명령문
confirm창
return
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>자바스크립트</title>
- <script>
- function hey(a,b){
- add = a+b;
- return 20;
- }
- document.write(hey(1,2));
- </script>
- </head>
- <body>
- </body>
- </html>
3을 반환하지 않고 20 을 반환
함수 참조
함수명(); -> 함수 호출
함수명; -> 함수 참조
함수 참조는 함수를 다른 변수에 대입 할수 있다.
- <script>
- function funcRef(){
- return "ref";
- }
- var hello = funcRef;
- document.write(hello());
- </script>
함수 표현식
함수 선언식
- function 함수명(){
- }
함수 표현식
- var sum = function(){
- };
- sum();
- <script>
- var sum = function(param1, param2 = 3, param3 = 10){
- document.write(param1 + param2 + param3 + '<br>');
- }
- sum(1);
- sum(1,2);
- sum(1,2,3);
- </script>
- </head>
함수 선언식은 함수를 먼저 호출하는 코드를 넣은후 함수 선언해도 상관없지만
함수 표현식은 함수가 먼저 선언한 후에 함수를 호출해야한다.
함수 화살표 표기법
- 변수(함수명) = () => 리턴할 값;
- <script>
- const arrowFunc = () => 'in arrow function';
- document.write(arrowFunc());
- </script>
() -> 파라미터 명
' ' -> '$(파라미터명)
- <script>
- const arrowFunc = year => `I was born ${year}`;
- document.write(arrowFunc(2005));
- </script>
- 변수(함수명) = 파라미터명 => { 명령문 };
- <script>
- const arrowFunc = sum => {
- const sumValue = sum + 10;
- return sumValue;
- };
- document.write(arrowFunc(2005));
- </script>
- </head>
- 변수(함수명) = (파라미터명,파라미터명) => 리턴할 값;
- <script>
- const arrowFunc = (num, num2) => num + num2;
- document.write(arrowFunc(1999,2020));
- </script>
hoisting(호이스팅)
함수선언식 호이스팅
- <script>
- hoisting();
- function hoisting(){
- document.write('I am here');
- }
- </script>
함수 선언전에 함수를 호출해도 결과가 잘 나타남
함수표현식 호이스팅
- <script>
- hoisting();
- const hoisting = function(){
- document.write('I am here');
- }
- </script>
함수 선언하고 호출
화살표표기법 호이스팅
- <script>
- document.write(hoisting());
- const hoisting = () => 'I am here';
- </script>
함수 선언하고 호출
변수선언 let
let 변수명 = 값;범위 : 블록 단위
- <script>
- let num = 11;
- if(true){
- let num = 20;
- document.write('num of inside is ' + num);
- }
- document.write('<br>num of outside is ' + num);
- </script>
- </head>
안이랑 밖 변수 num이 다르다.
범위 - 스코프(scope)
let 또는 const 사용하여 변수 또는 상수를 선언하면
해당 블록안에서만 작동한다.
전역변수
- <script>
- let score = 100;
- {
- score = 55;
- document.write('in block = ' + score);
- }
- document.write('<br>out block = ' + score);
- </script>
in block = 55
out block = 55
- <script>
- {
- const score = 100;
- document.write('first block ' + score);
- }
- {
- const score = 200;
- document.write('<br>second block = ' + score);
- }
- {
- const score = 300;
- document.write('<br>third block = ' + score);
- }
- </script>
블록 내의 서로 다른 상수
객체 생성
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>자바스크립트</title>
<script>
function make(){
this.name;
this.company;
this.color;
this.numPeople;
this.meth = show;
}
function show(){
document.write("이름 : "+this.name+"<br />");
document.write("회사 : "+this.company+"<br />");
document.write("인원 : "+this.numPeople +"<br />");
document.write("색상 : "+ this.color +"<br />");
}
r = new make();
r .name="sy";
r.company = "sk";
r.color = "pink";
r.numPeople = 2;
r.meth();
</script>
</head>
<body>
</body>
</html>
함수 파라미터 해제
연산자를 사용해 객체의 값에 접근
- <script>
- const myDeviceData = { name : 'sy', cpu : 'B', display : 9 };
- function myDevice(data){
- document.write(data.name + '<br>');
- document.write(data.cpu + '<br>');
- document.write(data.display);
- }
- myDevice(myDeviceData);
- </script>
객체의 키값으로 값에 접근
- <script>
- const myDeviceData = { name : 'sy', cpu : 'B', display : 9 };
- function myDevice({name, cpu, display}){
- document.write(`${name}` + '<br>');
- document.write(`${cpu}` + '<br>');
- document.write(`${display}`);
- }
- myDevice(myDeviceData);
- </script>
화면(모니터) 크기 알아내기
availHeight 는 상단 메뉴바와 하단 Dock Bar를 제외한 화면 세로길이
웹브라우저 창 크기 알아내기
자바스크립트에는 기본적으로 갖춘 객체 중 window객체가 있다.
window객체에는 웹브라우저에 대한 정보를 담고있다.
웹브라우저 가로 길이 = window.outerWidth
웹브라우저 세로 길이 = window.outerHeight
실제 웹페이지가 보이는 화면 가로 길이 = window.innerWidth
실제 웹페이지가 보이는 화면 세로 길이 = window.innerHeight
설렉터(선택자)
1.class selector
document.getElementsByClassName(클래스명)[순서];
script는 태그와 관련된 작업을 시작할때 HTML태그가 모두 로딩 된후 시작
window.onload = function(){ 코드 };
- <script>
- window.onload = function(){
- document.getElementsByClassName('hello')[2].style.color = "red";
- };
- </script>
- <body>
- <p class="hello">Hello World</p>
- <p class="hello">Hello World</p>
- <p class="hello">Hello World</p>
- <p class="hello">Hello World</p>
- <p class="hello">Hello World</p>
- <p class="hello">Hello World</p>
- <p class="hello">Hello World</p>
- </body>
p태그가 인지가 되고 3번째 hello world가 빨간색으로 변한다.
Tag Selector
document.getElementsByTagName(태그명)[순서];
- <script>
- window.onload = function(){
- document.getElementsByTagName('p')[5].style.color = "red";
- };
- </script>
document.getElementById(ID명);
- <script>
- window.onload = function(){
- document.getElementById('hello').style.color = "red"; //getElements -> getElement
- };
- </script>
- <body>
- <p>Hello World</p>
- <p>Hello World</p>
- <p>Hello World</p>
- <p id="hello">Hello World</p>
- <p>Hello World</p>
- <p>Hello World</p>
- <p>Hello World</p>
- <p>Hello World</p>
- </body>
querySelector 사용하기
- <script>
- window.onload = function(){
- document.querySelector('.hello').style.color = "blue";
- document.querySelector('p').style.color = "red";
- document.querySelector('#hello').style.color = "yellow";
- };
- </script>
- <body>
- <p>Hello World</p>
- <p class="hello">Hello World</p>
- <p class="hello">Hello World</p>
- <p id="hello">Hello World</p>
- <p>Hello World</p>
- <p>Hello World</p>
- <p>Hello World</p>
- <p>Hello World</p>
- </body>
순서 지정 X ->querySelectorAll (순서지정)
querySelectorAll 사용하기
- <script>
- window.onload = function(){
- document.querySelectorAll('.hello')[0].style.color = "blue";
- document.querySelectorAll('.hello')[1].style.color = "blue";
- document.querySelector('#hello').style.color = "yellow";
- document.querySelectorAll('p')[4].style.color = "red";
- document.querySelectorAll('p')[5].style.color = "red";
- };
- </script>
설렉터(선택자)의 텍스트 값 얻기(추출)와 변경하기
innerText를 사용하여 텍스트 얻는 방법
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<script>
window.onload = function(){
document.write('내가 좋아하는 강아지는 ' + document.getElementsByClassName('dog')[1].innerText);
}
</script>
</head>
<body>
<p class="dog">말티즈</p>
<p class="dog">리트리버</p>
<p class="dog">푸들</p>
</body>
</html>
innerText 사용하여 텍스트를 변경하는 방법
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<script>
window.onload = function(){
document.getElementsByClassName('dog')[1].innerText = "웰시코기"
}
</script>
</head>
<body>
<p class="dog">말티즈</p>
<p class="dog">리트리버</p>
<p class="dog">푸들</p>
</body>
</html>
설렉터(선택자)의 HTML 태그값 얻기(추출)와 변경하기
innerHTML 사용하여 HTML 태그를 얻는(추출) 방법
선택자.innerHTML
document.getElementById('dog').innerHTML
- <script>
- window.onload = function(){
- console.log(document.getElementsByClassName('dog')[1].innerHTML);
- }
- </script>
- <body>
- <p class="dog">
- <b>말티즈</b>
- </p>
- <p class="dog">
- <b>리트리버</b>
- </p>
- <p class="dog">
- <b>푸들</b>
- </p>
- </body>
innerHTML 사용하여 HTML 태그를 변경하는 방법
선택자.innerHTML = 변경할HTML태그
document.getElementById('os').innerHTML = "변경할 HTML 태그"
- <script>
- window.onload = function(){
- txt = document.getElementsByClassName('dog')[1].innerHTML;
- txt = '<i>' + txt + '</i>'
- document.getElementsByClassName('dog')[1].innerHTML = txt;
- }
- </script>
- <body>
- <p class="dog">말티즈</p>
- <p class="dog">리트리버</p>
- <p class="dog">푸들</p>
- </body>
태그의 개수(길이) 알아보기
선택자.length
1.document.getElementsByTagName('p').length;
클릭 이벤트 생성
1.inline방식
<p onClick="명령문">click here</p>
- <body>
- <p onClick="alert('Hi');">click here</p>
- </body>
2.script태그에서 클릭이벤트 발생시키기
선택자.addEventListener('이벤트 유형', function(){ 명령문; });
- <script>
- window.onload = function(){
- var target = document.getElementsByTagName('p')[0];
- target.addEventListener('click', function(){
- alert('Hi');
- });
- };
- </script>
마우스 이벤트 생성
<!--마우스 포인터를 올렸을때 mouseover
마우스 포인터를 뗐을때 mouseout
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>onmouseover event</title>
<script>
window.onload = function(){
var target = document.getElementsByTagName('p')[0];
target.addEventListener('mouseover', function(){
target.style.color = "pink";
});
target.addEventListener('mouseout', function(){
target.style.color = "black";
});
};
</script>
</head>
<body>
<p>here</p>
</body>
</html>-->
<!--마우스 버튼을 누른상태에서 mousedown
마우스 버튼을 떼면 mouseup
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>onmouseover event</title>
<script>
window.onload = function(){
var target = document.getElementsByTagName('p')[0];
target.addEventListener('mousedown', function(){
target.style.color = "pink";
});
target.addEventListener('mouseup', function(){
target.style.color = "black";
});
};
</script>
</head>
<body>
<p>here</p>
</body>
</html>-->
<!--inline 방식-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>onmouse event</title>
</head>
<body>
<p
onMouseover="this.style.color='red';"
onMouseout="this.style.color='black';"
onMousedown="this.style.color='yellow';"
onMouseup="this.style.color='pink';" >
here
</p>
</body>
</html>
스크롤 이벤트 생성
scroll 이벤트 사용방법
- document.addEventListener('scroll', function() {
- });
현재의 스크롤 값 확인
document.documentElement.scrollTop;
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>pinkcoding - JavaScript - onmouseover event</title>
- <script>
- document.addEventListener('scroll', function() {
- var Value = document.documentElement.scrollTop;
- console.log('Value is ' + currentScrollValue);
- });
- </script>
- <style>
- div{height:3000px}
- </style>
- </head>
- <body>
- <div></div>
- </body>
- </html>
체인지(변경) 이벤트 생성
1.inline 방식
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>change event</title>
</head>
<body>
<select onChange="alert(this.value)">
<option value="value">value</option>
<option value="value2">value2</option>
<option value="value3">value3</option>
</select>
</body>
</body>
</html>
2.script태그에서 체인지 이벤트 실행하기
선택자.addEventLister('이벤트 유형', function(){ 명령문; });
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>change event</title>
<script>
window.onload = function(){
var target = document.getElementsByTagName('select')[0];
target.addEventListener('change', function(){
alert(this.value);
});
};
</script>
</head>
<body>
<select>
<option value="말티즈">말티즈</option>
<option value="리트리버">리트리버</option>
<option value="푸들">푸들</option>
</select>
</body>
</html>
스타일 조정하기
선택자.style.background = "pink";
선택자.style.fontSize = "30px";
선택자{box-shadow:가로길이값 세로길이값 번짐 효과 그림자 색}
-> 선택자.style.boxShadow = "10px 10px 10px lightblue";
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>style</title>
<script>
window.onload = function(){
var target = document.getElementsByTagName('div')[0];
target.style.width = "500px";
target.style.height = "20px";
target.style.background = "pink";
target.style.boxShadow = "10px 10px 10px lightpink";
};
</script>
</head>
<body>
<div></div>
</body>
</html>
태그 속성 조정하기
태그에 속성을 추가하는 방법
선택자.setAttribute(속성명, 속성값)
<!--<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>attribute</title>
<script>
window.onload = function(){
var target = document.getElementsByTagName('p')[0];
target.setAttribute('class','hi');
};
</script>
</head>
<body>
<p>here</p>
</body>
</html>-->
속성의 값을 가져오는 방법
선택자.getAttribute(속성명)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>style</title>
<script>
window.onload = function(){
var target = document.getElementsByTagName('input')[0];
var attrValue = target.getAttribute('type');
console.log('attrValue is ' + attrValue);
};
</script>
</head>
<body>
<input type="button" />
</body>
</html>
-->
속성을 제거하는 방법
선택자.removeAttribute(속성명)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>style</title>
<script>
window.onload = function(){
var target = document.getElementsByTagName('input')[0];
var attrValue = target.getAttribute('type');
if(attrValue == "button"){
target.removeAttribute('type');
}
};
</script>
</head>
<body>
<input type="button" />
</body>
</html>-->
속성 유무 파악하기
선택자.hasAttribute(속성명);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>style</title>
<script>
window.onload = function(){
var target = document.getElementsByTagName('input')[0];
var attr = target.hasAttribute('type');
if(attr === false){
target.setAttribute('type','button');
target.setAttribute('value',"Button");
}
};
</script>
</head>
<body>
<input />
</body>
</html>
체크박스 체크하기
체크박스가 체크된 상태인지 아닌지 알아보는 방법
선택자.checked
체크박스를 체크상태로 만드는 방법
선택자.checked = true;
반대로 체크된 박스를 체크 안된 상태로 만드는 방법
선택자.checked = false;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>checkbox</title>
<script>
window.onload = function(){
document.getElementById('checked').checked = false;
document.getElementById('unchecked').checked = true;
};
</script>
</head>
<body>
<label for="checked">checked</label>
<input type="checkbox" id="checked" checked/>
<label for="unchecked">unchecked</label>
<input type="checkbox" id="unchecked" />
</body>
</html>
여러개의 체크박스 체크하기
name 속성만으로 선택자를 사용
document.getElementsByName(name속성의 값)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>checkbox</title>
<script>
window.onload = function(){
var hobbyAllBtn = document.getElementById('hobbySelectAllBtn');
var jobAllBtn = document.getElementById('jobSelectAllBtn');
var unHobbyAllBtn = document.getElementById('hobbyUnSelectAllBtn');
var unJobAllBtn = document.getElementById('jobUnSelectAllBtn');
hobbyAllBtn.addEventListener('click', function(){
checkedAll('hobby', true);
});
jobAllBtn.addEventListener('click', function(){
checkedAll('job', true);
});
unHobbyAllBtn.addEventListener('click', function(){
checkedAll('hobby', false);
});
unJobAllBtn.addEventListener('click', function(){
checkedAll('job', false);
});
function checkedAll(checkType, value){
for(var i = 0; i < document.getElementsByName(checkType).length; i++){
document.getElementsByName(checkType)[i].checked = value;
}
}
};
</script>
</head>
<body>
<input type="button" id="hobbySelectAllBtn" value="Select All Hobbies"/>
<input type="button" id="hobbyUnSelectAllBtn" value="Unselect All Hobbies"/>
<h3>What's your hobby?</h3>
<label>listening music<input type="checkbox" name="hobby" value="1"/></label>
<label>watching youtube<input type="checkbox" name="hobby" value="2"/></label>
<label>watching movie<input type="checkbox" name="hobby" value="3"/></label>
<label>making doll<input type="checkbox" name="hobby" value="4"/></label>
<label>cooking<input type="checkbox" name="hobby" value="5"/></label>
<label>coding<input type="checkbox" name="hobby" value="6"/></label>
<label>none<input type="checkbox" name="hobby" value="7"/></label>
<br>
<br>
<br>
<input type="button" id="jobSelectAllBtn" value="Select All Jobs"/>
<input type="button" id="jobUnSelectAllBtn" value="Unselect All Jobs"/>
<h3>What's your Job?</h3>
<label>business<input type="checkbox" name="job" value="1"/></label>
<label>operation<input type="checkbox" name="job" value="2"/></label>
<label>head hunter<input type="checkbox" name="job" value="3"/></label>
<label>president<input type="checkbox" name="job" value="4"/></label>
<label>driver<input type="checkbox" name="job" value="5"/></label>
<label>programmer<input type="checkbox" name="job" value="6"/></label>
<label>designer<input type="checkbox" name="job" value="7"/></label>
</body>
</html>
복습
라디오버튼 체크하기
라디오가 체크된 상태인지 아닌지 알아보는 방법
선택자.checked
라디오버튼을 체크 상태로 만드는 방법
선택자.checked = true;
라디오버튼을 체크 안된 상태로 만드는 방법
선택자.checked = false;
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>radiocheck</title>
- <script>
- window.onload = function(){
- document.getElementById('checked').checked = false;
- document.getElementById('unchecked').checked = true;
- };
- </script>
- </head>
- <body>
- <label for="checked">checked</label>
- <input type="radio" id="checked" checked/>
- <label for="unchecked">unchecked</label>
- <input type="radio" id="unchecked" />
- </body>
- </html>
input태그 업로드 파일명 출력하기
파일 업로드 태그에 선택한 파일의 정보 보기
선택자.files
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>다중 파일 입력폼</title>
- </head>
- <body>
- <form name="이 폼의 이름" action="이 데이터들을 받을 파일" method="post" enctype="multipart/form-data">
- <input type='file' id="myFile" name='' multiple/>
- </form>
- </body>
- </html>
파일 여러개 등록해보고
console에서
document.getElementById('myFile').files;
2개의 파일 선택
document.getElementById('myFile').files[0].name;
document.getElementById('myFile').files[1].name;
파일을 선택하면 선택한 파일명이 출력
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title>다중 파일 목록</title>
- <script>
- window.onload = function(){
- target = document.getElementById('myFile');
- target.addEventListener('change', function(){
- fileList = "";
- for(i = 0; i < target.files.length; i++){
- fileList += target.files[i].name + '<br>';
- }
- target2 = document.getElementById('showFiles');
- target2.innerHTML = fileList;
- });
- }
- </script>
- </head>
- <body>
- <form name="이 폼의 이름" action="이 데이터들을 받을 파일" method="post" enctype="multipart/form-data">
- <input type='file' id="myFile" name='' multiple/>
- </form>
- <div id="showFiles">
- </div>
- </body>
- </html>
타임스태프를 자바스크립트에서 표시할때
날짜 객체 생성
var date = new Date();
- var timestamp = 1476508607 * 1000; //밀리세컨트의 단위를 기준으로 한다.
- var date = new Date(timestamp);
- console.log('year is ' + date.getFullYear());
자바스크립트를 이용하여 특정 엘리먼트(태그) 이동하기
document.getElementById(엘리먼트이름).scrollIntoView();
페이스북 자바스크립트 SDK를 이용하여 자신의 웹페이지에서 페이스북 계정으로 로그인 하기