tags:

views:

28

answers:

2

Hello friends.

I have this code I am checking wheather checkbox i checked or not..

  $('#btnsubmit').click(function() {
        $('#Details input[type=checkbox]').each(function() {
            if ($(this).attr('checked')) {
                  alert("selected");
                  return false;
            } else {
                alert("please select atleast one user");
                return false;
            }
        });
    });

here var checked showing true or false..

I have deatils Fieldset in the view.. like that each field set having one check box.. like that there are three fieldsets with one check box..I need to know how many details checkbox is checked? can I loop each Details Fieldset to know how many details checkboxes are cheked?

thanks

+1  A: 

You can use the :checked selector and get the .length, like this:

$('#btnsubmit').click(function() {
  var len = $('#Details input[type=checkbox]:checked').length;
  if(len === 0) { //no checked ones were found, error
    alert("Please select at least one user.");
    return false;
  }
  // else { //Possibly present a success message
  //  alert(len + " checkboxes were selected, have a nice day!");
  //}
});

If you don't need to do anything if some are checked (seems like the most likely case), you can narrow it down to this:

$('#btnsubmit').click(function() {
  if($('#Details input[type=checkbox]:checked').length === 0) {
    alert("Please select at least one user.");
    return false;
  }
});
Nick Craver
+1  A: 

I'm not exactly sure what you're looking for here. Here's how to do it for one fieldset:

alert($('#Details input[type=checkbox]:checked').length); 

I made a little example you can try too: http://jsfiddle.net/nzLpr/

Ryley
This is not an equivalent check, for example `<input type="radio" />`....`:checked` matches more than checkboxes :)
Nick Craver
Ah good to know, I wasn't aware! Editing now...
Ryley
if I need to get the perticular span value from Fieldset?
kumar
You might need to post some HTML showing what you mean for that. Generally, you can use a selector like `$('#Details span').get(0).text()`, which would get you the text within the first span of the Details fieldset.
Ryley