HTML / Reference / input type="checkbox"

개요

  • checkbox는 여러 선택지를 제공하고, 사용자가 하나 또는 여러 개의 선택을 할 수 있게 하는 폼 요소입니다.
  • input 태그의 type="checkbox" 속성을 사용하여 체크박스를 생성합니다.

문법

<input type="checkbox" name="xxx" value="yyy" checked>
  • name : 전달할 값의 이름입니다.
  • value : 전달될 값입니다.
  • checked : 선택된 상태로 만듭니다.

예제 - 기본

  • Blue 또는 Red를 선택합니다. 둘 다 선택할 수 있습니다.(라디오 버튼은 하나만 선택할 수 있습니다.)
  • 아무것도 선택되지 않은 상태에서 시작합니다.
<!doctype html>
<html lang="ko">
  <head>
  <meta charset="utf-8">
    <title>HTML</title>
    <style>
      * {
        font-size: 16px;
        font-family: Consolas, sans-serif;
      }
    </style>
  </head>
  <body>
    <form method="get" action="form-action.html">
      <p>Color</p>
      <label><input type="checkbox" name="color" value="blue"> Blue</label>
      <label><input type="checkbox" name="color" value="red"> Red</label>
      <p><input type="submit" value="Submit"> <input type="reset" value="Reset"></p>
    </form>
  </body>
</html>

  • Blue를 체크하고 Submit 버튼을 클릭하면 color의 값으로 blue를 전송합니다.

  • 둘 다 체크하면 color의 값으로 blue와 red를 전송합니다.

예제 - checked

  • checked를 추가하면 선택된 상태에서 시작합니다.
<!doctype html>
<html lang="ko">
  <head>
  <meta charset="utf-8">
    <title>HTML</title>
    <style>
      * {
        font-size: 16px;
        font-family: Consolas, sans-serif;
      }
    </style>
  </head>
  <body>
    <form method="get" action="form-action.html">
      <p>Color</p>
      <label><input type="checkbox" name="color" value="blue" checked> Blue</label>
      <label><input type="checkbox" name="color" value="red"> Red</label>
      <p><input type="submit" value="Submit"> <input type="reset" value="Reset"></p>
    </form>
  </body>
</html>

예제 - 배열로 값 넘기기

  • []를 이용하여 값을 배열로 넘길 수 있습니다.
<?php
  $nb = $_POST[ "nb" ];
  echo implode( ",", $nb );
?>
<!doctype html>
<html lang="ko">
  <head>
  <meta charset="utf-8">
    <title>HTML</title>
    <style>
      * {
        font-size: 16px;
        font-family: Consolas, sans-serif;
      }
    </style>
  </head>
  <body>
    <form method="POST">
      <p><label><input type="checkbox" name="nb[]" value="01"> 01</label></p>
      <p><label><input type="checkbox" name="nb[]" value="02"> 02</label></p>
      <p><label><input type="checkbox" name="nb[]" value="03"> 03</label></p>
      <p><label><input type="checkbox" name="nb[]" value="04"> 04</label></p>
      <p><label><input type="checkbox" name="nb[]" value="05"> 05</label></p>
      <p><input type="submit" value="Submit"></p>
    </form>
  </body>
</html>