Check if checkbox is checked with jQuery

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?

I am using the following code, but it always returns the count of checked checkboxes regardless of id.



function isCheckedById(id) 
{
   alert(id);
   var checked = $(input[@id= + id + ]:checked).length;
   alert(checked);

 if (checked == 0) 
{

  return false;
   
} else 
{

  return true;
   

Text Copied From stackoverflow.com
on : Fri, Feb 05, 2010 Views : 1337766

Accepted Answer

IDs must be unique in your document, meaning that you shouldn't do this:

<input type=checkbox name=chk[] id=chk[] value=Apples /> <input type=checkbox name=chk[] id=chk[] value=Bananas /> 

Instead, drop the ID, and then select them by name, or by a containing element:

<fieldset id=checkArray>
  <input type=checkbox name=chk[] value=Apples />
   <input type=checkbox name=chk[] value=Bananas /> </fieldset> 

And now the jQuery:

var atLeastOneIsChecked = $('#checkArray:checkbox:checked').length > 0;
 
//there should be no space between identifier and selector  
// or, without the container:  var atLeastOneIsChecked = $('input[name=chk[]]:checked').length > 0;
 
Text Copied From stackoverflow.com
on : Fri, Feb 05, 2010

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp