Skip to content

Instantly share code, notes, and snippets.

@kosh-jp
Created December 2, 2018 11:29
Show Gist options
  • Select an option

  • Save kosh-jp/97879c37c42aaf436a891ac2e020742a to your computer and use it in GitHub Desktop.

Select an option

Save kosh-jp/97879c37c42aaf436a891ac2e020742a to your computer and use it in GitHub Desktop.

Revisions

  1. kosh-jp created this gist Dec 2, 2018.
    25 changes: 25 additions & 0 deletions calculate-checkbox-value.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    <!DOCTYPE html>
    <html>
    <head>
    <script
    src="https://code.jquery.com/jquery-3.3.1.slim.js"
    integrity="sha256-fNXJFIlca05BIO2Y5zh1xrShK3ME+/lYZ0j+ChxX2DA="
    crossorigin="anonymous"></script>
    <script type="text/javascript" src="calculate-checkbox-value.js"></script>
    </head>
    <body>
    <div class="price_sum">
    <form>
    <ul>
    <li><input type="checkbox" checked><span data-price="1">一円</span></li>
    <li><input type="checkbox"><span data-price="10">十円</span></li>
    <li><input type="checkbox" checked><span data-price="100">百円</span></li>
    <li><input type="checkbox"><span data-price="1000">千円</span></li>
    </ul>
    </form>
    </div>
    <div>
    <p>合計金額 : <span class="price_display"></span></p>
    </div>
    </body>
    </html>
    16 changes: 16 additions & 0 deletions calculate-checkbox-value.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    $(function(){
    calPrice();
    $("input").on("change", function(){
    calPrice();
    });

    function calPrice(){
    var totalPrice = 0;
    $(".price_sum li").each(function(){
    if ($(this).find("input").prop("checked")) {
    totalPrice += Number($(this).find("span").data("price"));
    }
    $(".price_display").text(totalPrice);
    });
    }
    });