■ソース
This file contains 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> | |
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1"> | |
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js" type="text/javascript" charset="UTF-8"></script> | |
</head> | |
<body> | |
</body> | |
<div>総人数:<div id="total"></div>人</div><br> | |
<br> | |
<br> | |
<ul> | |
<li><input type="text" id="count1">人</li> | |
<li><input type="text" id="count2">人</li> | |
<li><input type="text" id="count3">人</li> | |
<li><input type="text" id="count4">人</li> | |
<li><input type="text" id="count5">人</li> | |
</ul> | |
<script> | |
// ここにスクリプトを記述 | |
</script> | |
</html> |
This file contains 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() { | |
// 自動計算 | |
$("input[id^='count']").live('blur keypress change', function() { | |
var sum =0; | |
for(i=1; i < $("[id^='count']").length + 1; i++) { | |
var count = $("[id='count" + i + "']").val(); | |
count = count == ""? 0 : count; | |
sum += parseFloat(count); | |
} | |
$("#total").text(sum); | |
}); | |
}); |
■ちょっと解説
- リストはjsで自動生成しているので、『bind』ではなく、『live』でイベント拾ってます。
- リストは可変なので、idの前方一致で拾うようにしてます。もうちょっといい方法があるかな?
- あとは、for文で、そのリスト分回して、計算。
- 計算した結果をid="total"に入れて表示。
もうちょっと、高速化とか考えたいところです。。
0 件のコメント:
コメントを投稿