Yrtymd
Yrtymd

Reputation: 433

Check if at least one checkbox is checked without clicking

How to check without clicking on the buttons that at least one of selected checkboxes on the page is checked ? Thanks!

<script>
$('#filter').find('input[type="checkbox"]').each( function(){


   if ($('input[type="checkbox"]').is(":checked")){
     $('#status').text("yes");
   }
   else {
   $('#status').text("no");
   }

});
</script>

 <div id="filter">
<input id='id1' type='checkbox' />
<input id='id1' type='checkbox' />
<input id='id1' type='checkbox' />


</div>

<label id='status' />

Upvotes: 1

Views: 2441

Answers (2)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

by using .length

$('input[type="checkbox"]:checked').length !== 0

Demo

$(document).ready(function(){
    if($('#filter input[type="checkbox"]:checked').length !== 0){
      alert('one or more checked');
    }else{
      alert('Nothing checked');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="filter">
  <input id='id1' type='checkbox' />
  <input id='id1' type='checkbox' />
  <input id='id1' type='checkbox' />
</div>

Upvotes: 2

Prashant Shirke
Prashant Shirke

Reputation: 1423

First of all remove the # from the div id in HTML.

Also consider making checkbox ids unique.

And to check whether any checkbox is checked, you can get by following code.

$(document).ready(function(){

function updateStatus(){
 if ($('div#filter input:checked').length > 0 ){
    $('#status').text("yes");
 }
 else {
    $('#status').text("no");
 } 
}

$('div#filter input[type="checkbox"]').on("change",updateStatus); 
updateStatus(); 
});

Not aware about your use case but you can also check it by calling the function after every 1 second (or as per requirement) like below.

$(document).ready(function(){

function updateStatus(){
 if ($('div#filter input:checked').length > 0 ){
    $('#status').text("yes");
 }
 else {
    $('#status').text("no");
 } 
}

window.setInterval(updateStatus, 1000); 
});

Upvotes: 2

Related Questions