Reputation: 15
Hi all am trying add priority number using on change function for check box. While select the checkbox if it was checked need add it as 1.am having list of checkbox within a div I check any one checkbox need to mark it as one if select next means need to mark it as two by the way everything. Now the problem the event doesn't need to trigger while already marked checkbox here my working
<div class="it">
<label>
<input type="checkbox" class="span"/> 1
</label>
<label>
<input type="checkbox" class="span"/> 2
</label>
<label>
<input type="checkbox" class="span"/> 3
</label>
<label>
<input type="checkbox" class="span"/> 4
</label>
<br>
<span></span>
</div>
my jquery
$(function () {
var count = 0;
$('.span').on('change', function() {
if(this.checked) {
count ++;
$('span').text(count);
}
})
})
please help the count will added only once for a checkbox FIDDLE
Upvotes: 0
Views: 2141
Reputation: 122926
You can count the :checked
checkboxes. To display the number of checked checkboxes you can also use an attribute, see snippet.
$('.it [type=checkbox]')
.on('click', function() {
$('[data-count]').attr('data-count',$('.it [type=checkbox]:checked').length);
}
);
label {
display: block;
}
div label:after{
clear: right;
content: " ";
}
[data-count]:after {
content: attr(data-count)' checked';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="it">
<label><input type="checkbox" class="span"/> 1</label>
<label><input type="checkbox" class="span"/> 2</label>
<label><input type="checkbox" class="span"/> 3</label>
<label><input type="checkbox" class="span"/> 4</label>
<span data-count=0></span>
</div>
You don't need JQuery per se, by the way.
Upvotes: 2
Reputation: 136
Try this:
$(function () {
$('.span').on('change', function() {
$('span').text ( $( ".span:checked" ).length );
});
});
Upvotes: 0
Reputation: 178109
Assuming you want to count checked boxes I suggest this
$(function () {
$('.span').on('click', function() {
$('span').text($(".span:checked").length);
}).triggerHandler("click"); // handle reload and initial counter
});
div label {
display:block;
}
div label:after{
clear:right;
content:" ";
}
.badge {
float:right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="it">
<label>
<input type="checkbox" class="span"/> 1
</label>
<label>
<input type="checkbox" class="span"/> 2
</label>
<label>
<input type="checkbox" class="span"/> 3
</label>
<label>
<input type="checkbox" class="span"/> 4
</label>
<br>
<span></span>
</div>
Upvotes: 4
Reputation: 22721
Try this,
$(function () {
var count = 0;
$('.span').on('change', function() {
count = $('.span:checked').length;
$('span').text(count);
});
});
Upvotes: 0