Checkbox

여러 항목을 독립적으로 선택하거나 동의 여부를 확인합니다.

Live preview
컴포넌트를 조작하면 여기에 결과가 표시됩니다.
코드 보기
HTML
<sy-checkbox
  checked
  name="notifications"
  value="email"
  id="sample"
>알림 이메일 받기</sy-checkbox>

사용 가이드

#

여러 항목을 독립적으로 켜고 끌 때 사용합니다. 서로 배타적인 한 가지 값은 Radio로 선택하게 하세요.

  1. 오류 문구는 error 슬롯에 작성합니다.

    컴포넌트 안에 <span slot="error">오류 메시지</span>을 넣으세요. 글자뿐 아니라 링크 등 필요한 안내도 넣을 수 있습니다. noNativeValidity를 지원하는 입력은 이를 켜면 브라우저 팝업 대신 이 안내를 표시합니다. Switch는 항상 컴포넌트 아래에 오류를 표시합니다.

  2. 업무 규칙의 실패는 setCustomError()로 알립니다.

    예를 들어 서버가 중복된 값을 거절하면 error 슬롯의 문구를 바꾸고 setCustomError()를 호출하세요. 이 메서드에는 메시지 인자를 전달하지 않습니다. 사용자 지정 오류가 있으면 폼 제출도 차단됩니다.

  3. 해결 후 해제하고 제출 가능 여부를 확인합니다.

    clearCustomError()로 업무 규칙 오류를 해제하세요. required나 입력 형식 검사까지 해제되지는 않습니다. await checkValidity()는 true/false를, reportValidity()는 검사 결과와 오류 표시를 함께 제공합니다. name을 지정한 유효한 값은 제출 시 FormData로 읽습니다.

선택·해제

checked로 선택 상태를 관리합니다. 항목 하나를 바꿔도 다른 항목의 선택은 유지합니다.

일부 선택

indeterminate는 하위 항목의 일부만 선택되었음을 나타냅니다. 실제 checked 값은 앱에서 관리하세요.

예제

#

독립적인 복수 선택

각 항목을 따로 켜고 끌 수 있습니다.

AI 요청하기

다음 요소를 세로로 쌓아 줘. - sy-checkbox "디자인" — name: "teams", value: "0", checked: true - sy-checkbox "개발" — name: "teams", value: "1" - sy-checkbox "마케팅" — name: "teams", value: "2"

코드 보기
HTML
<div style="display:grid;gap:16px;width:100%">
  <sy-checkbox
    name="teams"
    value="0"
    checked
  >디자인</sy-checkbox>
  <sy-checkbox name="teams" value="1">개발</sy-checkbox>
  <sy-checkbox name="teams" value="2">마케팅</sy-checkbox>
</div>

일부 선택 상태

일부 항목이 선택됐음을 표현합니다. 누르면 사용자가 명확한 선택 상태로 바꿀 수 있습니다.

AI 요청하기

다음 컴포넌트를 만들어 줘. - sy-checkbox "전체 선택" — indeterminate: true

코드 보기
HTML
<sy-checkbox indeterminate>전체 선택</sy-checkbox>

비활성화와 읽기 전용

위에서부터 기본 상태, 비활성화, 읽기 전용입니다. 비활성화 항목은 포커스와 입력이 차단됩니다. 읽기 전용은 값을 유지하면서 수정을 막습니다.

AI 요청하기

다음 요소를 세로로 쌓아 줘. - sy-checkbox "이메일 알림" — checked: true - sy-checkbox "이메일 알림" — checked: true, disabled: true - sy-checkbox "이메일 알림" — checked: true, readonly: true

코드 보기
HTML
<div style="display:grid;gap:16px;width:100%">
  <sy-checkbox checked>이메일 알림</sy-checkbox>
  <sy-checkbox checked disabled>이메일 알림</sy-checkbox>
  <sy-checkbox checked readonly>이메일 알림</sy-checkbox>
</div>

이벤트와 전달 값

컴포넌트를 조작하고 최근 이벤트의 이름과 detail 값을 확인하세요. 코드에는 이 컴포넌트와 하위 구성 요소가 보내는 이벤트의 구독 방법이 모두 포함되어 있습니다.

AI 요청하기

다음 컴포넌트를 만들어 줘. - sy-checkbox "알림 이메일 받기" — checked: true, name: "notifications", value: "email" 최근 이벤트 표시: changed, focused, blured

코드 보기
HTML
<sy-checkbox
  checked
  name="notifications"
  value="email"
  id="sample"
>알림 이메일 받기</sy-checkbox>
<output id="demo-events" aria-live="polite">컴포넌트를 조작하면 최근 이벤트와 전달 값이 표시됩니다.
</output>

<script type="module">
  const describeResult = value => JSON.stringify(value, (_key, item) => {
    if (item instanceof File) return {
      name: item.name,
      size: item.size,
      type: item.type
    };
    if (item instanceof Element) return `<${item.localName}>`;
    return item;
  }) ?? '완료';
  for (const name of ["changed", "focused", "blured"]) {
    document.addEventListener(name, event => {
      document.querySelector('#demo-events').textContent =
        `${event.target.localName} · ${name}: ${describeResult(event.detail)}`;
    });
  }
</script>

체크박스 보조 설명

checkboxTitle은 내부 체크박스의 title에 전달됩니다. 기본 슬롯에는 화면에 보일 문구를, title에는 추가 설명을 지정하세요.

AI 요청하기

다음 컴포넌트를 만들어 줘. - sy-checkbox "알림 이메일 받기" — checked: true, title: "프로젝트의 변경 사항을 이메일로 받습니다.", name: "notifications", value: "email" - JS 속성 checkboxTitle: "프로젝트의 변경 사항을 이메일로 받습니다."

코드 보기
HTML
<sy-checkbox
  checked
  title="프로젝트의 변경 사항을 이메일로 받습니다."
  name="notifications"
  value="email"
  id="sample"
>알림 이메일 받기</sy-checkbox>

<script type="module">
  const component1 = document.querySelector("#sample");
  Object.assign(component1, {
    "checkboxTitle": "프로젝트의 변경 사항을 이메일로 받습니다."
  });
</script>

폼과 유효성 검사

값을 비운 채 제출하면 필수 입력 검사가 동작합니다. 값을 입력한 뒤 제출해 폼 데이터를 확인하고, 사용자 지정 오류도 켜고 꺼보세요.

AI 요청하기

다음 컴포넌트를 만들어 줘. 폼 안에 넣어 줘. - sy-checkbox "약관에 동의합니다." — name: "field", required: true, value: "accepted" - span "동의가 필요합니다." (error 슬롯) 각 요소의 따옴표 안 문구를 그대로 유지해 줘. 슬롯 자식이 있어도 부모 요소의 문구를 생략하지 마.

코드 보기
HTML
<form style="display:grid;gap:16px">
  <sy-checkbox
    name="field"
    required
    value="accepted"
    id="sample"
  >약관에 동의합니다.<span slot="error">동의가 필요합니다.</span></sy-checkbox>
  <div style="display:flex;flex-wrap:wrap;gap:8px">
    <sy-button type="submit" variant="primary">제출</sy-button>
    <sy-button type="reset">초기화</sy-button>
  </div>
</form>
<div class="demo-actions"
  style="display:flex;flex-wrap:wrap;gap:8px;margin-top:16px"
>
  <sy-button id="action-0" size="small">유효성 확인</sy-button>
  <sy-button id="action-1" size="small">오류 표시</sy-button>
  <sy-button id="action-2" size="small">오류 해제</sy-button>
</div>
<output id="demo-result" aria-live="polite"></output>

<script type="module">
  const describeResult = value => JSON.stringify(value, (_key, item) => {
    if (item instanceof File) return {
      name: item.name,
      size: item.size,
      type: item.type
    };
    if (item instanceof Element) return `<${item.localName}>`;
    return item;
  }) ?? '완료';
  const actionTarget0 = document.querySelector("#sample");
  document.querySelector('#action-0').addEventListener('click', async () => {
    const result = await actionTarget0.checkValidity();
    document.querySelector('#demo-result').textContent = describeResult(result);
  });
  const actionTarget1 = document.querySelector("#sample");
  document.querySelector('#action-1').addEventListener('click', async () => {
    const result = await actionTarget1.setCustomError();
    document.querySelector('#demo-result').textContent = describeResult(result);
  });
  const actionTarget2 = document.querySelector("#sample");
  document.querySelector('#action-2').addEventListener('click', async () => {
    const result = await actionTarget2.clearCustomError();
    document.querySelector('#demo-result').textContent = describeResult(result);
  });
  document.querySelector('form').addEventListener('submit', event => {
    event.preventDefault();
    document.querySelector('#demo-result').textContent = describeResult([...new FormData(event
      .currentTarget)]);
  });
</script>

검사 결과와 오류 상태 읽기

제출 전에 검사하거나 오류를 화면에 표시할 수 있습니다. 필수 값을 비워 두고 검사한 다음, 값을 채워 반환 값이 어떻게 달라지는지 확인하세요. 상태 조회는 사용자 지정 오류와 필수 입력 오류를 구분하는 데 사용합니다.

AI 요청하기

다음 컴포넌트를 만들어 줘. 폼 안에 넣어 줘. - sy-checkbox "약관에 동의합니다." — name: "field", required: true, value: "accepted" - span "동의가 필요합니다." (error 슬롯) 각 요소의 따옴표 안 문구를 그대로 유지해 줘. 슬롯 자식이 있어도 부모 요소의 문구를 생략하지 마. 버튼 추가: "오류와 함께 검사" → reportValidity(), "검증 상태 조회" → getValidStatus()

코드 보기
HTML
<form style="display:grid;gap:16px">
  <sy-checkbox
    name="field"
    required
    value="accepted"
    id="sample"
  >약관에 동의합니다.<span slot="error">동의가 필요합니다.</span></sy-checkbox>
  <div style="display:flex;flex-wrap:wrap;gap:8px">
    <sy-button type="submit" variant="primary">제출</sy-button>
    <sy-button type="reset">초기화</sy-button>
  </div>
</form>
<div class="demo-actions"
  style="display:flex;flex-wrap:wrap;gap:8px;margin-top:16px"
>
  <sy-button id="action-0" size="small">유효성 확인</sy-button>
  <sy-button id="action-1" size="small">오류 표시</sy-button>
  <sy-button id="action-2" size="small">오류 해제</sy-button>
  <sy-button id="action-3" size="small">오류와 함께 검사</sy-button>
  <sy-button id="action-4" size="small">검증 상태 조회</sy-button>
</div>
<output id="demo-result" aria-live="polite"></output>

<script type="module">
  const describeResult = value => JSON.stringify(value, (_key, item) => {
    if (item instanceof File) return {
      name: item.name,
      size: item.size,
      type: item.type
    };
    if (item instanceof Element) return `<${item.localName}>`;
    return item;
  }) ?? '완료';
  const actionTarget0 = document.querySelector("#sample");
  document.querySelector('#action-0').addEventListener('click', async () => {
    const result = await actionTarget0.checkValidity();
    document.querySelector('#demo-result').textContent = describeResult(result);
  });
  const actionTarget1 = document.querySelector("#sample");
  document.querySelector('#action-1').addEventListener('click', async () => {
    const result = await actionTarget1.setCustomError();
    document.querySelector('#demo-result').textContent = describeResult(result);
  });
  const actionTarget2 = document.querySelector("#sample");
  document.querySelector('#action-2').addEventListener('click', async () => {
    const result = await actionTarget2.clearCustomError();
    document.querySelector('#demo-result').textContent = describeResult(result);
  });
  const actionTarget3 = document.querySelector("#sample");
  document.querySelector('#action-3').addEventListener('click', async () => {
    const result = await actionTarget3.reportValidity();
    document.querySelector('#demo-result').textContent = describeResult(result);
  });
  const actionTarget4 = document.querySelector("#sample");
  document.querySelector('#action-4').addEventListener('click', async () => {
    const result = await actionTarget4.getValidStatus();
    document.querySelector('#demo-result').textContent = describeResult(result);
  });
  document.querySelector('form').addEventListener('submit', event => {
    event.preventDefault();
    document.querySelector('#demo-result').textContent = describeResult([...new FormData(event
      .currentTarget)]);
  });
</script>

사용자 지정 오류 메시지

서버 중복 검사나 업무 규칙에 맞지 않을 때 오류 문구를 직접 표시합니다. 아래 문구를 바꿔 보고 제출을 눌러 차단되는지 확인하세요. 오류 해제 후에는 필수 입력 조건까지 만족해야 제출됩니다.

코드 보기
HTML
<label for="error-message">표시할 오류 메시지</label><input
  id="error-message"
  value="서버에서 이 값을 승인하지 않았습니다. 내용을 확인해 주세요."
  type="text"
>
<form style="display:grid;gap:16px">
  <sy-checkbox
    no-native-validity
    name="field"
    required
    value="accepted"
    id="sample"
  >약관에 동의합니다.<span slot="error">동의가 필요합니다.</span></sy-checkbox>
  <div style="display:flex;flex-wrap:wrap;gap:8px">
    <sy-button type="submit" variant="primary">제출</sy-button>
    <sy-button type="reset">초기화</sy-button>
  </div>
</form>
<div class="demo-actions">
  <sy-button id="show-custom-error" variant="primary">오류 표시</sy-button>
  <sy-button id="clear-custom-error">오류 해제</sy-button>
</div>
<output id="custom-error-result" aria-live="polite"></output>
<output id="demo-result" aria-live="polite"></output>

<script type="module">
  const describeResult = value => JSON.stringify(value, (_key, item) => {
    if (item instanceof File) return {
      name: item.name,
      size: item.size,
      type: item.type
    };
    if (item instanceof Element) return `<${item.localName}>`;
    return item;
  }) ?? '완료';
  await (async function customErrorSetup(root) {
    const field = root.querySelector('#sample');
    const message = root.querySelector('[slot="error"]');
    const input = root.querySelector('#error-message');
    const output = root.querySelector('#custom-error-result');
    const update = async () => {
      message.textContent = input.value.trim() || _msg("m_4eea8cef81c6");
      await field.setCustomError();
      output.textContent = _msg("m_e00bd46236d3", [message.textContent]);
    };
    input.addEventListener('input', update);
    root.querySelector('#show-custom-error').addEventListener('click', update);
    root.querySelector('#clear-custom-error').addEventListener('click', async () => {
      await field.clearCustomError();
      output.textContent = await field.checkValidity() ? _msg("m_c454251167b2") : _msg(
        "m_5b8cb48627e5");
    });
    root.querySelector('form').addEventListener('invalid', () => {
      output.textContent = _msg("m_c702c7778166");
    }, true);
    root.querySelector('form').addEventListener('reset', () => {
      output.textContent = _msg("m_b90c2b4dc30f");
    });
    await update();
  })(document);
  document.querySelector('form').addEventListener('submit', event => {
    event.preventDefault();
    document.querySelector('#demo-result').textContent = describeResult([...new FormData(event
      .currentTarget)]);
  });
</script>

API reference

#

이름에 마우스를 올리거나 키보드로 선택하면 적용 코드를 확인할 수 있습니다. 터치 화면에서는 이름을 누르세요.

<sy-checkbox>

Properties

Attribute / PropertyTypeDefaultDescription
string''체크박스에 표시할 title 속성입니다.
string''FormData에 사용되는 필드 이름입니다.
string'on'현재 값 또는 항목의 식별 값입니다.
booleanfalse선택 또는 켜짐 상태입니다.
booleanfalse사용자 조작과 키보드 포커스를 차단합니다.
booleanfalse일부 항목만 선택된 중간 상태입니다.
booleanfalse현재 값을 보여주면서 사용자 수정을 막습니다.
booleanfalse값이 없으면 폼 검증을 실패시킵니다.
booleanfalse브라우저의 기본 오류 표시 대신 앱의 오류 UI를 사용할 때 지정합니다. checkValidity 검사 자체는 유지됩니다.

Events

EventDetailDescription
CustomEvent<{ value: boolean; isValid: boolean; checked: boolean; indeterminate: boolean }>값 또는 선택 상태가 바뀔 때 발생합니다.
CustomEvent<boolean>포커스를 받으면 발생합니다.
CustomEvent<boolean>포커스를 잃으면 발생합니다.

Methods

MethodReturnsDescription
Promise<void>입력 또는 동작 요소에 키보드 포커스를 보냅니다.
Promise<void>입력 요소에서 포커스를 해제합니다.
Promise<boolean>현재 제약 조건에 맞으면 true, 아니면 false를 반환합니다.
Promise<boolean>현재 값을 검사하고 오류를 사용자에게 표시합니다.
Promise<string>현재 유효성 검사 상태를 반환합니다.
Promise<void>사용자 지정 오류 상태를 설정합니다.
Promise<void>사용자 지정 오류 상태를 해제합니다.

Slots

SlotDescription
컴포넌트의 본문 또는 자식 항목입니다.
유효성 검사 오류 메시지입니다.