zaterdag 9 oktober 2010

Get value from Checkboxlist clientside using Javascript

My latest (SharePoint) assignment was to modify the OOB “Send to –> Other location” functionality. The customer wanted to select the target lists using a checkboxlist control instead of having to type URL’s manually. To make this work I made a copy of the application page Copy.aspx and modified it slightly. It turned out that SharePoint was doing some clientside checks, for which it needed the value of the selected items in my checkboxlist control.

Quite some searching and Googling taught me that it is not possible to retrieve the value clientside using the standard checkboxlist control, but I did find a way to retrieve the value from a checkboxcontrol. To make this possible I needed to make my very own control.

This custom control should be made in the following way:

namespace Your.NameSpace
{
    public class CustomCheckBoxListControl : CheckBoxList, IRepeatInfoUser
    {
        void IRepeatInfoUser.RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
        {
            writer.WriteBeginTag("input");
            writer.WriteAttribute("type", "checkbox");
            writer.WriteAttribute("name", UniqueID + "$" + repeatIndex);
            writer.WriteAttribute("id", ClientID + "_" + repeatIndex.ToString(NumberFormatInfo.InvariantInfo));
            writer.WriteAttribute("value", Items[repeatIndex].Value);
            System.Web.UI.AttributeCollection attrs = Items[repeatIndex].Attributes;
            foreach (string key in attrs.Keys)
            {
                writer.WriteAttribute(key, attrs[key]);
            }

            writer.Write(">");
            writer.Write(Items[repeatIndex].Text);
        }
    }
}

As you can see, the value from the listitem is rendered along with the rest of the standard HTML. This means that we can now access the value clientside. Just to be complete, the javascript to retrieve the value of the first checked item could look like this:

var checkedItemValue;

for (i = 0; i < 100; i++)
{
    var checkbox = document.getElementById("<%SPHttpUtility.NoEncode(myCheckBoxList.ClientID,Response.Output);%>_" + i );

    if (checkbox == null)
    {
        break;
    }

    if (checkbox.checked)
    {
        checkedItemValue = checkbox.value;
        break;
    }
}

1 opmerking:

  1. Geen werving en selectiebureaus, enkel werkgevers! Solliciteer dus rechtstreeks bij de werkgever. Check jouw ict vacature!

    BeantwoordenVerwijderen