views:

63

answers:

2

Hi,

In my asp.net website; i have REPEATER control having child control checklistbox , dynamically generates in code behind.

I would like to know how can i write javascript function where i have to check at least one checkbox should be checked.

Ho can i acheive? Please Help?

+2  A: 

You could wrap the list of checkboxes in a container (e.g. a <div>) with a known ID:

<div id="myCheckboxes">
  <input type="checkbox" ...>
  <!-- ... -->
  <input type="checkbox" ...>
</div>

And then in JavaScript do:

function isOneChecked(containerId) {
  var myDiv = document.getElementByID(containerId);
  if (myDiv != null) {
    var checkBoxes = myDiv.getElementsByTagName("INPUT");

    for (var i=0; i<checkBoxes.length; i++) {
      if (checkBoxes[i].checked == true) {
        return true;
      }
    }
  }
  return false;
}

and call it as:

if (isOneChecked("myCheckboxes")) {
  // whatever
}
Tomalak
In my case i am using checklistbox inside REPEATER control. Does it require to find repeater control first. Then find checklist? How?
Hemant Kothiyal
@Hermant: OK, let me rephrase my first sentence for you: *You could wrap the **repeater** in a container (e.g. a `<div>`)...*
Tomalak
+1  A: 

The jQuery way:

if($('input[type=checkbox]:checked').length > 0){
  alert('At least one check box is checked')
}

P.S. If it not a problem use frameworks, you can choose form variety of them(jQuery, Prototype, MooTools, Dojo etc.). They will make your life easier and your javascript code more crossbrowser compatible.

Ilian Iliev
Limiting it to a certain container would be necessary in jQuery, too.
Tomalak
Yeah, I'd add the asp:repeaters clientID into the jQuery selector: $('#<%=repeaterID.ClientId%> input[type=checkbox]:checked')
toxaq
You are both right, but the code above is just an example for the jQ way, there is no original html provided so I have skipped the container id part to make it more clear.
Ilian Iliev
Your answer is right but for completeness, if the asker doesn't know how to add the repeated selector in, I thought it'd be nice to know. I didn't want to add another answer basically duplicating yours. On second look, are you sure your logic is right? Shouldn't it be length < 1 ?
toxaq
"at least one checkbox should be checked" so the number of checked boxes must be greater than 0, am I right?
Ilian Iliev