HTML / input / checkbox / 체크박스 만들기
목차
체크박스
- 체크박스는 클릭하면 선택되고, 다시 클릭하면 선택이 해제되는 사각형 모양의 박스이다.
- 체크박스는 input 태그로 만든다.
문법
<input type="checkbox" name="xxx" value="yyy" checked>
- name : 전달할 값의 이름이다.
- value : 전달될 값이다.
- checked : 선택된 상태로 만든다.
예제 1 - 기본
- 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를 전송한다.
예제 2 - 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>
예제 3 - 배열로 값 넘기기
- []를 이용하여 값을 배열로 넘길 수 있다.
<?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>