Pages

Tuesday 9 April 2013

Access Repeater Control Items with JavaScript

Basic Problem here is how to access the items within Repeater Control Template like say for example you have repeater control Item template like below
<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <table>
            <tr>
              <td><asp:Label ID="Label1" runat="server" Text='<%#Eval("Username")%>' ></asp:Label></td>
            </tr>
            <tr>
              <td>
                  <asp:TextBox ID="TextBox1"  Text='<%#Eval("Password")%>' runat="server"></asp:TextBox>
                   </td>
              </tr>
        </table>
    </ItemTemplate>
</asp:Repeater>
To  access repeater control Item from JavaScript many methods are available like some one will use to iterate DOM Elements of it Row by Row using JavaScript / use JQuery to do that.
now in looping method of access normally people traverse the DOM element like DIV>TR>TD and access the specified item . we will be approaching some more easy way to access that .
To Access the Item directly by ID we will use document.getElementById() method of JavaScript to locate Label and TextBox Directly of Specified index.but how we will know ID of Label and TextBox ?
well when Asp.net generates Item within Repeater it follows some pattern like “ParentControlID_ChildControlID_IndexOfItem” if you have set ClientIDMode="Predictable".We will use this pattern to locate item Directly instead of looping by JavaScript so lets make a JavaScript function which takes one argument Index as parameter and alert a value of TextBox and Label.
<script type="text/javascript">
function Access(ItemIndex)
{
      var LabelID = "Repeater1_Label1_" + ItemIndex;
      var TextBoxID = "Repeater1_TextBox1_" + ItemIndex;

      var LabelValue = document.getElementById(LabelID).innerText;
      var TextBoxValue = document.getElementById(TextBoxID).value;

      alert("Label Value=" + LabelValue + " TextBoxValue=" + TextBoxValue);
}
</script>
and access the function by providing ItemIndex as Argument to function in button like this
<input type="button" onclick="Access(0);" value="Access Items"/>
Access Repeater Control Items with JavaScript

No comments:

Post a Comment