숫자 더하기 부분 질문드립니다....

숫자 더하기 부분 질문드립니다....

QA

숫자 더하기 부분 질문드립니다....

본문

반복질문 죄송합니다.

 

 

<?php echo number_format($ct_price['stotal']); ?>여기값에 들어가있는

숫자내용을 한곳에 다더한 내용을 나오게끔 하고싶은데.. 

스크립트 때문인지 구글로 다 찾아봐도 합계가 안되고 

 

내용이 10개가 있다면  금액이 더하기가 안되고 1개의 값만 나오더라구요..

ㅜㅜ 관련 내용이나 방법좀 알려주시면 감사하겠습니다.

 

초보인 사람에게는 너무 어렵네요 ㅠㅠ

 

 


<?php
         $chk_cnt = 0;
        for($i=0; $row=sql_fetch_array($result); $i++) {
            // 상품이미지
            $image = get_it_image($row['it_id'], 50, 50);
            // 상품의 옵션정보
            $sql = " select ct_id, it_id, ct_price, ct_point, ct_qty, ct_option, ct_status, cp_price, ct_stock_use, ct_point_use, ct_send_cost, io_type, io_price
                        from {$g5['g5_shop_cart_table']}
                        where od_id = '{$od['od_id']}'
                          and it_id = '{$row['it_id']}'
                        order by io_type asc, ct_id asc ";
            $res = sql_query($sql);
            $rowspan = sql_num_rows($res);
            // 합계금액 계산
            $sql = " select SUM(IF(io_type = 1, (io_price * ct_qty), ((ct_price + io_price) * ct_qty))) as price,
                            SUM(ct_qty) as qty
                        from {$g5['g5_shop_cart_table']}
                        where it_id = '{$row['it_id']}'
                          and od_id = '{$od['od_id']}' ";
            $sum = sql_fetch($sql);
            // 배송비
            switch($row['ct_send_cost'])
            {
                case 1:
                    $ct_send_cost = '착불';
                    break;
                case 2:
                    $ct_send_cost = '무료';
                    break;
                default:
                    $ct_send_cost = '선불';
                    break;
            }
            // 조건부무료
            if($row['it_sc_type'] == 2) {
                $sendcost = get_item_sendcost($row['it_id'], $sum['price'], $sum['qty'], $od['od_id']);
                if($sendcost == 0)
                    $ct_send_cost = '무료';
            }
            for($k=0; $opt=sql_fetch_array($res); $k++) {
                if($opt['io_type'])
                    $opt_price = $opt['io_price'];
                else
                    $opt_price = $opt['ct_price'] + $opt['io_price'];
                // 소계
                $ct_price['stotal'] = $opt_price * $opt['ct_qty'];
                $ct_point['stotal'] = $opt['ct_point'] * $opt['ct_qty'];
            ?>
            <tr style="    height: 100px;">
                <?php if($k == 0) { ?>
                 <td rowspan="<?php echo $rowspan; ?>" class="td_chk" >
    <?php echo $i+1; ?> </td>
                <td rowspan="<?php echo $rowspan; ?>" class="td_left">
                    <a href="./itemform.php?w=u&it_id=<?php echo $row['it_id']; ?>"><?php echo $image; ?> <?php echo stripslashes($row['it_name']); ?></a>
                    <?php if($od['od_tax_flag'] && $row['ct_notax']) echo '[비과세상품]'; ?>
                </td>
               
                <?php } ?>
               <td><?php $it= sql_fetch("select it_maker , it_basic from {$g5['g5_shop_item_table']} where  it_id = '{$row['it_id']}' "); ?><?php echo $it['it_maker']; ?> </td>
                <td class="td_left">
          <?php $it= sql_fetch("select it_origin , it_basic from {$g5['g5_shop_item_table']} where  it_id = '{$row['it_id']}' "); ?> <?php echo $it['it_origin']; ?> 
                </td>
               <td class="td_num">
                    <label for="ct_qty_<?php echo $chk_cnt; ?>" class="sound_only" value="<?php echo $opt['ct_qty']; ?>"> 수량</label>
                    <span class="quantity"><?php echo $opt['ct_qty']; ?></span>
                </td>
                  <td class="td_num_right "><input type="text" name="opt_price" class="price" value="<?php echo number_format($opt_price); ?>"  onKeyup="inputNumberAutoComma(this);"> </td>
                <td class="td_num_right"><span class="calc_price"><?php echo number_format($ct_price['stotal']); ?></span></td>
             
            </tr>

 
             
            <?php
                $chk_cnt++;
            }
            ?>
        <?php
        }
        ?>

 


<script>
// 반복되는 부분 말고, 한번만 출력되면 OKAY
$('.price').on('keyup', function() {
    var quantity = parseInt($(this).closest('tr').find('.quantity').text().replace(/[^\d]+/g, '')) | 0;
    var price = parseInt($(this).val().replace(/[^\d]+/g, '')) | 0;
    $(this).closest('tr').find('.calc_price').text(quantity*price);
        $(this).closest('tr').find('.calc_price').text(new Intl.NumberFormat().format(quantity*price));
});
   function inputNumberAutoComma(obj) {
       
        // 콤마( , )의 경우도 문자로 인식되기때문에 콤마를 따로 제거한다.
        var deleteComma = obj.value.replace(/\,/g, "");
        // 콤마( , )를 제외하고 문자가 입력되었는지를 확인한다.
        if(isFinite(deleteComma) == false) {
            alert("문자는 입력하실 수 없습니다.");
            obj.value = "";
            return false;
        }
       
        // 기존에 들어가있던 콤마( , )를 제거한 이 후의 입력값에 다시 콤마( , )를 삽입한다.
        obj.value = inputNumberWithComma(inputNumberRemoveComma(obj.value));
    }
   
    // 천단위 이상의 숫자에 콤마( , )를 삽입하는 함수
    function inputNumberWithComma(str) {
        str = String(str);
        return str.replace(/(\d)(?=(?:\d{3})+(?!\d))/g, "$1,");
    }
    // 콤마( , )가 들어간 값에 콤마를 제거하는 함수
    function inputNumberRemoveComma(str) {
        str = String(str);
        return str.replace(/[^\d]+/g, "");
    }
</script>

이 질문에 댓글 쓰기 :

답변 2

이론 상 정상 작동하리라 봅니다. 기존의 코드 거의 그대로니까 이해 후 응용&활용하기를….

쓴소리 생략….


$('.price').on('keyup', function() {
    var quantity = parseInt($(this).closest('tr').find('.quantity').text().replace(/[^\d]+/g, '')) | 0;
    var price = parseInt($(this).val().replace(/[^\d]+/g, '')) | 0;
    $(this).closest('tr').find('.calc_price').text(quantity*price);
    $(this).closest('tr').find('.calc_price').text(new Intl.NumberFormat().format(quantity*price));
 
    var total_price = 0;
    $('.price').each(function() {
        var q = parseInt($(this).closest('tr').find('.quantity').text().replace(/[^\d]+/g, '')) | 0;
        var p = parseInt($(this).val().replace(/[^\d]+/g, '')) | 0;
        total_price+= q*p;
    });
    // 원하는 위치에 아래 결과물 대입
    // new Intl.NumberFormat().format(total_price)
});

답변감사합니다..
제가 이쪽은 아예 몰라서.. 죄송합니다.

결과물 대입하는곳에

<? new Intl.NumberFormat().format(total_price)?>
이렇게 해봐도 안나오는데 어떻게 해야할까요.

윽...
안되나봅니다... ㅜㅜ 정성스럽게 답변 주셨는데 제가 무지해서..죄송합니다..


  <span id="total_price">0</span>


<script>
// 반복되는 부분 말고, 한번만 출력되면 OKAY
$('.price').on('keyup', function() {
    var quantity = parseInt($(this).closest('tr').find('.quantity').text().replace(/[^\d]+/g, '')) | 0;
    var price = parseInt($(this).val().replace(/[^\d]+/g, '')) | 0;
    $(this).closest('tr').find('.calc_price').text(quantity*price);
    $(this).closest('tr').find('.calc_price').text(new Intl.NumberFormat().format(quantity*price));
 
    var total_price = 0;
    $('.price').each(function() {
        var q = parseInt($(this).closest('tr').find('.quantity').text().replace(/[^\d]+/g, '')) | 0;
        var p = parseInt($(this).val().replace(/[^\d]+/g, '')) | 0;
        total_price+= q*p;
    });
    // 원하는 위치에 아래 결과물 대입
    // new Intl.NumberFormat().format(total_price)
});

</script>

예제 코드 남깁니다. (구현 방법은 이 외에도 다양합니다.)


<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<table border="1" style="width:100%;">
    <tr>
        <td><span class="quantity">2</span></td>
        <td><input type="text" class="price" value="1000"></td>
        <td><span class="calc_price"></span></td>
    </tr>
    <tr>
        <td><span class="quantity">1</span></td>
        <td><input type="text" class="price" value="2000"></td>
        <td><span class="calc_price"></span></td>
    </tr>
</table>
<span id="total_price"></span>
<script>
function calc_total_price() {
    var total_price = 0;
    $('.price').each(function() {
        var q = parseInt($(this).closest('tr').find('.quantity').text().replace(/[^\d]+/g, '')) | 0;
        var p = parseInt($(this).val().replace(/[^\d]+/g, '')) | 0;
        var calc = q*p;
        $(this).closest('tr').find('.calc_price').text(new Intl.NumberFormat().format(calc));
        total_price+= calc;
    });
    $('#total_price').text(new Intl.NumberFormat().format(total_price));
}
$('.price').on('keyup', function() {
    var quantity = parseInt($(this).closest('tr').find('.quantity').text().replace(/[^\d]+/g, '')) | 0;
    var price = parseInt($(this).val().replace(/[^\d]+/g, '')) | 0;
    $(this).closest('tr').find('.calc_price').text(new Intl.NumberFormat().format(quantity*price));
    calc_total_price();
});
$(document).ready(function() {
    calc_total_price();
});
</script>

탈 jQuery 추세이긴 하지만 쓰기 나름이니…. (생략)

* Selector

- https://api.jquery.com/category/selectors/

- .find() : https://api.jquery.com/find/

- .text() : https://api.jquery.com/text/

:

쓴소리 생략.

답변을 작성하시기 전에 로그인 해주세요.
전체 0
QA 내용 검색
  • 개별 목록 구성 제목 답변작성자조회작성일
  • 질문이 없습니다.

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT