비전공자 개발일기

HTML Checkbox 본문

HTML _CSS

HTML Checkbox

HiroDaegu 2021. 9. 2. 00:31
728x90
SMALL
<h3>checkbox 연습</h3>
    <h4>선택된 box의 value 확인</h4>
    <p>
      h.w.1) All select 선택 시 모든 checkbox 선택<br>
      h.w.2) checkbox의 선택이 바뀌면 선택된 항목 출력(check 된것만 출력)
    </p>
    <form>
      <label>
        check1 : <input type="checkbox" name="test" value="box1" onclick="allClear()" onchange="getCheckboxValue(this)">
      </label>
      <label>
        check2 : <input type="checkbox" name="test" value="box2" onclick="allClear()" onchange="getCheckboxValue(this)">
      </label>
      <label>
        check3 : <input type="checkbox" name="test" value="box3" onclick="allClear()" onchange="getCheckboxValue(this)">
      </label>
      <label>
        All select : <input type="checkbox" name="selectAll" value="all" onclick="allClick(this)" onchange="getCheckboxValue()">
      </label>
      <p>
        <!-- test:[value, value, ...] -->
        선택된 항목 : <span id=result></span>
      </p>
    </form>
<script>
  function allClick(allCheck) {
    let checkAll = document.querySelectorAll('[type="checkbox"]')
    // console.log(checkAll)
    checkAll.forEach((checkbox) => {
      checkbox.checked = allCheck.checked
    })
  }

  function allClear() {
    let allBoxes = document.querySelectorAll('[name="test"]')
    let checked = document.querySelectorAll('input[name="test"]:checked')
    let all = document.querySelector('[name="selectAll"]')
    
    if(allBoxes.length === checked.length)  {
    all.checked = true;
  }else {
    all.checked = false;
  }
}

  function getCheckboxValue(checkbox)  {
  let span = document.querySelector('#result')
  const query = 'input[name="test"]:checked';
  const selectedEls = document.querySelectorAll(query);
  
  let result = '';
  selectedEls.forEach((el) => {
    result += el.value + ' ';
  });

  span.innerText= result;   
}
  

</script>
728x90
LIST

'HTML _CSS' 카테고리의 다른 글

CSS BULMA, TAILWIND  (0) 2021.09.17
HTML Checkbox 2  (0) 2021.09.03
HTML CANVAS  (0) 2021.08.31
HTML SVG  (0) 2021.08.30
HTML IFrame  (0) 2021.08.29