views:

186

answers:

4

I need to write a java script. This is supposed to validate if the checkbox is selected in the page or not. The problem here is that the check box is inside a grid and is generated dynamically. The reason being the number of check box that need to be rendered is not know at design time. So the id is know only at the server side.

A: 

If it's your only checkbox you can do a getElementsByTagName() call to get all inputs and then iterate through the returned array looking for the appropriate type value (i.e. checkbox).

wykyd
+1  A: 

You have to generate your javascript too, or at least a javascript data structure (array) wich must contain the checkboxes you should control.

Alternatively you can create a containing element, and cycle with js on every child input element of type checkbox.

Anonymous
+1  A: 

Here is a thought:

As indicated by Anonymous you can generate javascript, if you are in ASP.NET you have some help with the RegisterClientScriptBlock() method. MSDN on Injecting Client Side Script

Also you could write, or generate, a javascript function that takes in a checkbox as a parameter and add an onClick attribute to your checkbox definition that calls your function and passes itself as the parameter

function TrackMyCheckbox(ck)
{
     //keep track of state
}

<input type="checkbox" onClick="TrackMyCheckbox(this);".... />
TheZenker
A: 

There is not much detail in the question. But assuming the the HTML grid is generated on the server side (not in javascript).

Then add classes to the checkboxes you want to ensure are checked. And loop through the DOM looking for all checkboxes with that class. In jQuery:

HTML:

<html>
...

<div id="grid">
   <input type="checkbox"  id="checkbox1" class="must-be-checked" />
   <input type="checkbox"  id="checkbox2" class="not-validated" />
   <input type="checkbox"  id="checkbox3" class="must-be-checked" />
   ...      
   <input type="checkbox"  id="checkboxN" class="must-be-checked" />
</div>

...
</html>

Javascript:

<script type="text/javascript">

  // This will show an alert if any checkboxes with the class 'must-be-checked'
  // are not checked.
  // Checkboxes with any other class (or no class) are ignored
  if ($('#grid .must-be-checked:not(:checked)').length > 0) {
    alert('some checkboxes not checked!');
  }

</script>
Karl