Reputation: 1025
I know this may seem like an amateur problem but I am having trouble selecting all the checkboxes on page load using Jquery. I figured it out with pure JS.
Also, once that problem is solved I need to iterate through all checkboxes and see if they are all checked. If they are, alert the user they are all selected, if not all of them are selected then alert the user another message.
I have put together a simple Jsfiddle to help get started. Any help would be appreciated.
<table>
<tr>
<th>Days of Week</th>
<td>
<div class="checkbox-group" id="checkboxes">
<ul>
<li>
<input type="checkbox" id="mon"/>
<label for="mon">MON</label>
</li>
<li>
<input type="checkbox" id="tue"/>
<label for="tue">TUE</label>
</li>
<li>
<input type="checkbox" id="wed"/>
<label for="wed">WED</label>
</li>
<li>
<input type="checkbox" id="thur"/>
<label for="thur">THUR</label>
</li>
<li>
<input type="checkbox" id="fri"/>
<label for="fri">FRI</label>
</li>
<li>
<input type="checkbox" id="sat"/>
<label for="sat">SAT</label>
</li>
<li>
<input type="checkbox" id="sun"/>
<label for="sun">SUN</label>
</li>
</ul>
</div>
<span id="allChecked" style="display:block; width:425px; text-align:center; color:#999999;">
(all days selected)
</span>
</td>
</tr>
Upvotes: 2
Views: 16264
Reputation: 168051
$( document ).ready( function(){
var checkboxes = $( ':checkbox' );
// Check all checkboxes
checkboxes.prop( 'checked', true );
// Check if they are all checked and alert a message
// or, if not, alert something else.
if ( checkboxes.filter( ':checked' ).length == checkboxes.length )
alert( 'All Checked' );
else
alert( 'Not All Checked' );
});
or if you want to update the span
:
$( document ).ready( function(){
var checkboxes = $( ':checkbox' ),
span = $( '#allChecked' );
checkboxes.prop( 'checked', true );
checkboxes.on( 'change', function(){
var checked = checkboxes.filter( ':checked' );
if ( checked.length == checkboxes.length )
span.text( '(All Days Selected)' );
else
{
var days = jQuery.map( checked, function(n){return n.id;} );
span.text( '(' + days.join(', ') + ' Selected)' );
}
} );
});
Upvotes: 5
Reputation: 25100
$(function(){
$('[type=checkbox]').attr({'checked':'checked'});
var checkedArray = [] ;
$.each($('[type= checkbox]'),function(index,value){
if($(this).attr('checked') == 'checked')
checkedArray.push($(this).attr('id'));
});
console.log(checkedArray.length);
//["mon", "tue", "wed", "thur", "fri", "sat", "sun"]
});
checkedArray
array will have a list of id
of the checked checkbox
And you can do checkedArray.length
to get the array length
Upvotes: 0
Reputation: 3089
Please go through the link below that shows various ways to achieve the same:
Check all checkboxes on page load with jQuery
Hope this helps. Thanks, Jatin
Upvotes: 0
Reputation: 342
$(document).ready(function(){
$(':checkbox').attr('checked',true);
});
I just tried it in your JSFiddle link and it works.
Upvotes: 0