반응형

자바스크립트 radio(라디오버튼) 객체의 뜻과 간단예제


라디오 버튼은 체크 박스와 다르게 여러 개 중에서 하나만을 선택하고자 할 때 필요한 객체이다. 역시 radio 객체도 form 객체의 하위 객체이다. 항상 form 객체를 지정해야만 radio 객체를 사용할 수 있다.



속 성 

내 용 

name 

radio 객체의 이름을 지정할 때 사용한다 

value 

객체에 값을 입력해주고자 할 때 사용한다 

length 

객체의 수를 지정해준다. 

checked 

객체가 선택이 되었는지 않았는지에 대해서 알 수 있다. 

defaultChecked 

웹 브라우저 문서를 읽을 때 처음부터 radio 객체를 디폴트로 지정해준다. 

type 

객체의 형태를 지정해준다. 




간단 예제에서는 라디오 객체의 checked 속성에 대해서 살펴보자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>라디오 버튼 선택 예제</title>
        <script>
            function select(form) {
                for (var start = 0; start < form.subject.length; start++) {
                    if (form.subject[start].checked == true) {
                        alert(form.subject[start].value + " 과목을 선택했습니다.")
                    }
                }
            }
        </script>
    </head>
    <body>
        <h3>좋아하는 과목은?</h3>
        <form action="nothingcgi">
            <input type="radio" name="subject" value="언어" checked>언어<br>
            <input type="radio" name="subject" value="외국어">외국어<br>
            <input type="radio" name="subject" value="수리">수리<br>
            <input type="radio" name="subject" value="과학탐구">과학탐구<br>
            <input type="radio" name="subject" value="음악">음악<br>
            <input type="radio" name="subject" value="체육">체육<br>
 
            <input type="button" value="확인" onclick="select(this.form)">
        </form>
    </body>
</html>
 
cs






이번 간단 예제는 onClick 이벤트 핸들러를 이용해서 브라우저의 배경색을 바꿔보자


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
 
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>라디오 버튼을 이용한 이벤트 핸들러 예제</title>
        <script>
            function color(sub) {
                document.bgColor = sub.value
            }
        </script>
    </head>
    <body>
        <h3>색깔 물들이기</h3>
        <form action="nothingcgi">
            <input type="radio" name="sub" value="red" onclick="color(this)" checked>언어<br>
            <input type="radio" name="sub" value="black" onclick="color(this)">외국어<br>
            <input type="radio" name="sub" value="yellow" onclick="color(this)">수리<br>
            <input type="radio" name="sub" value="white" onclick="color(this)">과학탐구<br>
            <input type="radio" name="sub" value="blue" onclick="color(this)">음악<br>
            <input type="radio" name="sub" value="pink" onclick="color(this)">체육<br>
 
        </form>
    </body>
</html>
 
cs






반응형
Posted by 제3인생자
l