Reputation: 1873
$(document).ready(function() {
function countChecked() {
var n = $("input:checked").length;
$("div").text(n + (n <= 1 ? " is" : " are") + " checked!");
}
countChecked();
$(":checkbox").click(countChecked);
});
div {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="newsletter" checked="checked" value="Hourly" />
<input type="checkbox" name="newsletter" value="Daily" />
<input type="checkbox" name="newsletter" value="Weekly" />
<input type="checkbox" name="newsletter" checked="checked" value="Monthly" />
<input type="checkbox" name="newsletter" value="Yearly" />
</form>
I need to get the value of all the checked checkboxes like "Hourly", "Daily"
how can I get all the value of the checked checkboxes can anybody help me, please
Upvotes: 0
Views: 4221
Reputation: 3212
slight improvement on Pim Jager (guessing you want an array of the values returned):
function getCheckedNames(){
var arr = new Array();
var $checked = $('[@name=newsletter]:checked');
$checked.each(function(){
arr.push($(this).val());
});
return arr;
}
and with the improvement from duckyflip:
function getCheckedNames(){
return jQuery('[@name=newsletter]:checked').map(function(){
return this.value;
});
}
Upvotes: 1
Reputation: 16499
var values = $.makeArray($(":checkbox:checked").map(function(){
return this.value
})).join(', ')
alert(values)
Upvotes: 1
Reputation: 32119
I think this is what you are after:
function updateChecked(){
var arr = new Array();
$('input:checkbox:checked').each( function() {
arr.push($(this).val());
});
var checkboxesText = arr.join(', ');
var moreText = (arr.length <= 1 ? " is" : " are") + ' checked!';
$('div').text(checkboxesText + moreText);
}
This would set the div text to something like: "Hourly, Daily are checked!"
Upvotes: 0
Reputation: 37741
Not easy to see what you're trying to do here, but I'm guessing this is what you're after:
$("input:checked").each(function() {
alert($(this).val());
});
Upvotes: 0