Web/Javascript

Show Hide 자바스크립트 CheckBox

qOOp 2008. 7. 4. 18:05
반응형

Show Hide 자바스크립트 CheckBox

<html>

<head>

<script>

function showHideBox(obj) {

              var box = document.getElementById('dispBox');       // ShowHide 대상

              if(obj.checked) {

                            box.style.display = "block";    // display속성을 block로 지정. Block와 줄바꿈을 함

                            // box.style.display = "inline";              // inline 와 줄바꿈이 없음

              } else {

                            box.style.display = "none";    // display 속성을 보이지 없앰.

              }

}

</script>

</head>

<body>

<input type="checkbox" onclick="showHideBox(this);" /> <input type="text" size="20" id="dispBox" style="display:none;" />

</body>

</html>

 

체크박스의 이벤트 핸들러의 경우에는 onclick 이다. 클릭을 할경우 showHideBox(this) 를 호출한다.

Obj.checked 로 체크박스 객체가 체크되었는지 유무를 확인한다.

 

위의 소스를 이용하여 여러곳에서 사용이 가능한 소스로 변경.

 

<html>

<head>

<script>

function showHideBox(obj,target) {              // target 인자를 추가

              var box = document.getElementById(target);             // 당연히 target으로 바꿈             

              if(obj.checked) {

                            //box.style.display = "block";

                            box.style.display = "inline";

              } else {

                            box.style.display = "none";

              }

}

</script>

</head>

<body>

<input type="checkbox" onclick="showHideBox(this,'dispBox');" /> <input type="text" size="20" id="dispBox" style="display:none;" /><br />

<input type="checkbox" onclick="showHideBox(this,'dispBox1');" /> <input type="text" size="20" id="dispBox1" style="display:none;" />

</body>

</html>

 

ShowHide를 시킬 대상의 이름을 함수에 함께 포함시켜서 대상의 이름변경만으로 여러곳에서 사용이 가능하다.