본문 바로가기
프로그래밍/HTML, CSS, JavaScript

체크박스 클릭 시 해당 테이블 줄 배경색 변경하기

by [바가지] 2018. 7. 25.
반응형

체크박스 클릭 시 해당 테이블 줄 배경색 변경하기

 

 

테이블 안 체크박스를 클릭하면 해당 Row의 배경 색이 변경되는 코딩 방법을 알아 보도록 하겠습니다.

자바스크립트를 사용하여 간단하게 체크 된 라인의 배경색을 변경 할 수 있습니다.

먼저 전체 소스를 살펴 보도록 하겠습니다.

 

  전체소스

<!DOCTYPE html>
<head>
  <title>체크박스 클릭 시 해당 테이블 줄 배경색 변경하기</title>
  <script>
    function setBg(t) {
      td = t.parentNode;
      td.style.backgroundColor = (t.checked) ? "blue" : "white";

      tr = t.parentNode.parentNode;
      tr.style.backgroundColor = (t.checked) ? "#FFBB00" : "#fff";
    }
  </script>
</head>
<body>

 
  <table width="100%;" border=1 cellspacing=0 cellpadding=5>
     <tr>
       <td width=20><input type="checkbox" onclick="setBg(this)"></td>
       <td>이런조이</td>
     </tr>
     <tr>
       <td><input type="checkbox" onclick="setBg(this)"></td>
       <td>체크박스 체크하면</td>
     </tr>
     <tr>
       <td><input type="checkbox" onclick="setBg(this)"></td>
       <td>테이블의 체크 된 라인의 색이 변경 됩니다</td>
     </tr>
  </table>
 

</body>
</html>

 

  설명

1. 자바스크립트 호출

  <input type="checkbox" onclick="setBg(this)">

onclick="setBg(this)"

체크박스를 클릭 했을 경우 setBg 함수를 호출하게 됩니다. this란 현재 자신의 정보를 객체로 보내게 됩니다.

 

2. 호출 자바스크립트

  function setBg(t) {
    td = t.parentNode;
    td.style.backgroundColor = (t.checked) ? "blue" : "white"; 
    tr = t.parentNode.parentNode;
    tr.style.backgroundColor = (t.checked) ? "#FFBB00" : "#fff";
  }

setBg(t)

넘겨준 this는 t라는 변수명으로 받게 됩니다.

t.parentNode

넘어 온 객체(t)의 부모노드(parentNode)를 가리키게 됩니다. 따라서 체크박스 상위의 노드는 <td> 가 됩니다.

td.style.backgroundColor = (t.checked) ? "blue" : "white"; 

<td>의  배경색을 변경 합니다. 만약 체크되어 있다면 blue 체크 안되어 있다면 white 로 변경 합니다.

※ 판단대상 ? 참이면적용 : 거짓이면적용

tr = t.parentNode.parentNode;

체크박스객체.부모노드.부모노드 의 객체는 <tr> 이 됩니다.

tr.style.backgroundColor = (t.checked) ? "#FFBB00" : "#fff";

<tr>의 배경색을 변경 하게 됩니다.

 

  결과

※ 만약 t.parentNode 의 배경색을 설정하지 않았다면 전체 노란색으로 변경 되었을 것 입니다.

 

체크박스 클릭 시 결과

 

  실습

이런조이
체크박스 체크하면
테이블의 체크 된 라인의 색이 변경 됩니다

 

HTML 과 자바스크립트를 이용한 테이블 안 체크박스를 클릭 했을 경우 해당 줄의 색을 변경하는 코딩을 알아 보았습니다.

 

반응형