Wednesday, September 12, 2007

Minutia of a Javascript Checkbox

An overlooked aspect of the Javascript checkbox is, unlike it's asp:checkbox brother, you can group them together with one name and view the values on the server side. In this example, a checkbox is placed in an asp:datagrid. An asp:repeater would work the same way.

This would go in the datagrid/repeater:
<input type="checkbox" name="VALUEChkBx" value='<%#DataBinder.Eval(Container.DataItem, "aValue")%>' onclick="return VALUEChkBx_Click(this, event);">
----------------------------------------------------------------------------
On the page you could add some javascript functionality by taking advantage of the onclick attribute:
function VALUEChkBx_Click(src, e)
{
  var f = src.form;
  f.EmailBtn.disabled = true;

  for (i=0, j=f.length; i<j; i++)
  {
    var ele = f[i];
    if (ele.name == "VALUEChkBx" && ele.checked)
    {
      f.EmailTxt.disabled = false;
      f.EmailBtn.disabled = false;

      break;
    }
  }
}
---------------------------------------------------------------------------
Now for the intricate part, the code behind:
string valueList = Request.Form["VALUEChkBx"];
if (valueList != null && valueList.Length != 0)
{
  string [] aList = valueList.Split(',');

  for(int i=0; i<aList.Length; i++)
  {
    string value = aList[i].ToString();

**Notice that aList holds each individual value of the checkboxes that were checked on the page. Take special note to request the checkbox(s) using the form - Request.Form["VALUEChkBx"]

No comments: