체크박스 체크값의 합을 구하고 싶습니다.
본문
<input type="checkbox" name="type_00" value="PC" <?if($w_type[0]):?> checked<?endif;?>>
PC
<input type="checkbox" name="type_01" value="PC Print" <?if($w_type[1]):?> checked<?endif;?>>
PC Print
체크박스를 체크한 수만큼의 합계를 구하고 싶습니다.
PC 체크박스를 클릭했다면 PC체크박스를 몇번 클릭했는지 숫자로 나타내주고 싶습니다.
PC=3번 이렇게요
어떻게 구현하면 될까요?
답변 2
JavaScript
<script>
jQuery(function () {
var $type = jQuery("[data-bind-type]"),
$disp = jQuery("div#dispCheckedCount");
$type.bind("click", function () {
var data = {};
$disp.empty();
$type.each(function () {
if( this.checked === true )
{
var type = jQuery(this).attr("data-bind-type")
className = "dispCheckedItem-"+type;
if( typeof data[type] == "undefined" )
{
$disp.append("<p class='"+className+"'>"+type+"=<span class='count'>1</span></p>");
data[type] = 1;
}
else
{
data[type]++;
$disp.find("p." + className + " > span.count").text(data[type]);
}
}
});
});
});
</script>
HTML
<input type="checkbox" name="type_00" value="PC" data-bind-type="PC"> PC
<input type="checkbox" name="type_01" value="PC Print" data-bind-type="PC">PC Print
<input type="checkbox" name="type_01" value="16GB" data-bind-type="memory">memory 16GB
<input type="checkbox" name="type_01" value="32GB" data-bind-type="memory">memory 32GB
<div id="dispCheckedCount">
대충이런식이 아닐까요?
!-->
$("input[type='checkbox']").click( function() {
var val = $(this).val(), m = val.match(/([^\d]+)(\d+)/);
if (!$.isArray(m)) $(this).val(val + '=1');
else $(this).val( m[1] + (Number(m[2]) + Number(1)) );
});
답변을 작성하시기 전에 로그인 해주세요.