Created
December 2, 2018 11:29
-
-
Save kosh-jp/97879c37c42aaf436a891ac2e020742a to your computer and use it in GitHub Desktop.
jQuery/calculate-checkbox-value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment