본문 바로가기

퍼블리싱/HTML | CSS | Javascript

버튼 클릭시 input 값이 증감되는 소스

See the Pen plus minus input by publisher.kim (@publisherkim) on CodePen.


html

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<div class="count_area">
    <button class="btn_minus">-</button>
    <input type="number" value="1" class="counter">
    <button class="btn_plus">+</button>
</div>
<br>
<div class="count_area">
    <button class="btn_minus">-</button>
    <input type="number" value="1" class="counter">
    <button class="btn_plus">+</button>
</div>

 

css

.count_area{overflow:hidden;}
.count_area *{box-sizing:border-box;}
.count_area input[type=number]{height:30px; border:1px solid #ddd;float:left; border-left:0; border-right:0; width:30px; text-align:center;}
.count_area input[type=number]::-webkit-inner-spin-button {appearance: none;-moz-appearance: none;-webkit-appearance: none;}
.count_area .btn_minus, 
.count_area .btn_plus{display:inline-block; width:30px; height:30px; font-size:15px; float:left; border:1px solid #ddd; cursor:pointer;}
.count_area .btn_minus{border-radius:5px 0 0 5px;}
.count_area .btn_plus{border-radius:0 5px 5px 0;}

 

js *jquery 필요

$(document).ready(function () {
  $(".btn_minus").click(function () {
    var inputElement = $(this).siblings(".counter");
    var currentValue = parseInt(inputElement.val());
    // 값이 1 이상일 때만 감소
    if (currentValue > 1) {
     inputElement.val(currentValue - 1);
    }
  });

  $(".btn_plus").click(function () {
    var inputElement = $(this).siblings(".counter");
    var currentValue = parseInt(inputElement.val());
    inputElement.val(currentValue + 1);
  });
});

 

따봉 챗지피티야 고마워!

728x90