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

2020-08-31 (월) 15:06:02 3,165

반복질문 죄송합니다.

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

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

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

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

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

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

Copy
<?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&amp;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
        }
        ?>
Copy
<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개 / 댓글 3개

2020-08-31 (월) 19:36:02

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

Copy
<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/

:

쓴소리 생략.

2020-08-31 (월) 15:57:19

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

쓴소리 생략….

Copy
$('.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)
});

답변에 대한 댓글 3개

2020-08-31 (월) 16:14:39
답변감사합니다..
제가 이쪽은 아예 몰라서.. 죄송합니다.

결과물 대입하는곳에

<? new Intl.NumberFormat().format(total_price)?>
이렇게 해봐도 안나오는데 어떻게 해야할까요.
총합 <span id="total_price">0</span>

$('#total_price')...
2020-08-31 (월) 17:41:39
윽...
안되나봅니다... ㅜㅜ 정성스럽게 답변 주셨는데 제가 무지해서..죄송합니다..


<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>

답변을 작성하려면 로그인이 필요합니다.