check box를 사용해서 선택한 물품의 결제 금액 계산하기

안시우·2024년 5월 3일

목록 보기
3/3

1. 설명

  • input type="checkbox" :
    사용시 check box가 생성되고, 각각 항목은 선택하거나 선택하지 않을 수 있다. 즉, 각 항목은 독립적이다.
  • input value="80000" :
    벨류 값은 서버에 보내지거나 현재 값을 가져와 처리한다.
  • label :
    • input의 id를 label의 for에 넣어주면, 글자를 선택하였을 때에도 check box가 선택된다.
    • input type="checkbox" name="hat" id="hat" value="10000"
      label for="hat"
  • input readonly :
    사용자는 입력할 수 없고, 보기만 가능하다.
  • parseInt(sum.value) :
    벨류 값은 문자열 타입이다. 따라서 계산하기 위해서 parseInt() 함수를 사용하여 숫자 타입으로 바꾸어 준다.
  • obj.checked :
    리턴 값이 boolean 타입이다. check box를 선택했다면 true, 선택하지 않았다면 false를 반환한다.
  • onclick="sumCalc(this)" :
    • onclick : check box 클릭했을 때
    • this : this가 쓰여졌던 바로 그 테그 자신

2. 코드

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>물품을 선택하면 금액 자동계산</title>
  <script>
    function sumCalc(obj){
      let sum = document.querySelector("#sum");
      if(obj.checked){
        sum.value = parseInt(sum.value) + parseInt(obj.value);
      }else{
        sum.value = parseInt(sum.value) - parseInt(obj.value);
      }
    }
  </script>
</head>
<body>
  <h1>물품을 선택하면 금액이 자동계산됩니다.</h1>
  <hr>
  <input type="checkbox" name="hat" id="hat" value="10000" onclick="sumCalc(this)">
  <label for="hat">모자 1만원</label>
  <input type="checkbox" name="bag" id="bag" value="80000" onclick="sumCalc(this)">
  <label for="bag">가방 8만원</label>
  <input type="checkbox" name="shoes" id="shoes" value="30000" onclick="sumCalc(this)">
  <label for="shoes">구두 3만원</label>
  <label for="sum">지불하실금액</label>
  <input type="number" name="sum" id="sum" readonly value="0">
</body>
</html>

3. 결과



0개의 댓글