# Wednesday, October 20, 2010
« Visual Studio 2010 and Visual SourceSafe... | Main | Printing to a network printer from ASP.N... »

We had a situation with one of our applications were the team felt it was easier to use straight html to do some work in a form.  All went pretty well until we created a checkbox input array:

<input type="checkbox" name="CheckboxArray" />
<input type="checkbox" name="CheckboxArray" />
<input type="checkbox" name="CheckboxArray" />
<input type="checkbox" name="CheckboxArray" />

and we retrieved them via the Request.Form(“CheckboxArray”).

image

We discovered when we tried to retrieve the array only the checked items were being returned and their position in the array is lost. 

image

Which ones are on? We can’t assume it’s the first and second one.

Solution:

Give the checkboxes a value that uniquely identifies it.

<input type="checkbox" name="CheckboxArray" value="1" />
<input type="checkbox" name="CheckboxArray" value="2" />
<input type="checkbox" name="CheckboxArray" value="3" />
<input type="checkbox" name="CheckboxArray" value="4" />

Now when you retrieve the array it returns the values of the checkboxes that are checked.

image

What if you want to return all the checkboxes whether they are on or off?  A little more work is needed in this case.  We’ll add a hidden field array for each of our checkboxes and will have these fields keep the status of our checkboxes.

<input type="checkbox" name="CheckboxArray2" /><input type="hidden" name="CheckboxFix" value="false" />
<input type="checkbox" name="CheckboxArray2" /><input type="hidden" name="CheckboxFix" value="false" />
<input type="checkbox" name="CheckboxArray2" /><input type="hidden" name="CheckboxFix" value="false" />
<input type="checkbox" name="CheckboxArray2" /><input type="hidden" name="CheckboxFix" value="false"/>

We’ll use jQuery to help with keeping the status.

<script type="text/javascript">
    $(document).ready(function () {
      $("[name=CheckboxArray2]").click(function () {
        $(this).next("[name=CheckboxFix]").val($(this).attr("checked"));
    });
}); 
</script>

Now in the code behind we’ll use the CheckboxFix instead of using the CheckboxArray2 in the Request.Forms call.

image

In our case we went with this second option because we were using jQuery on the client to enable the user to add, delete and reorder the rows of information.  Using the latter technique allowed us to easily work with the submitted data in a similar manner with the rest of the items in each row.

Happy Coding!

OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: b, blockquote@cite, em, i, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview