AnaMaria
AnaMaria

Reputation: 3621

Can't access textbox for Autocomplete in repeater

I'm trying to access a textbox in a repeater using a small javascript script. It's called by an ajax autocomplete when the user chooses an option from the list.

It's not working because the javascript can't access the textbox (ID=ContactID). The reason is because it's in a repeater. So how do I modify the script to access that particular textbox in the repeater?

<script type="text/javascript" >
    function OnContactSelected(source, eventArgs) {
    $get('<%# ContactID.ClientID %>').value = eventArgs.get_value();
    }
</script>

Repeater code:

<asp:repeater ID="itemsRepeater" 
      OnItemDataBound="itemsRepeater_ItemDataBound" 
      runat="Server">
   <itemtemplate>
      <tr>
         <td>
          <asp:RadioButtonList runat="server"  DataSource="<%#         ((Outlet)Container.DataItem).OutletInformations %>" DataValueField="DateOfDelivery" DataTextField="DateOfDelivery" />        
         </td>
         <td>
            <asp:TextBox ID="ContactID" runat="server"/>
         </td>
      </tr>
   </itemtemplate>
</asp:repeater>

Upvotes: 1

Views: 733

Answers (1)

MaxPRafferty
MaxPRafferty

Reputation: 4977

It would seem that your issue is that you are not actually targeting any "particular" textbox. There will be one such textbox for every single row of your repeater, and because of the nature of databinding, those textboxes will always only be available at runtime.

To fix this, you need to do one of two things. The harder, but more complete answer is to use the repeater's onItemDatabound event and pull the child controls from this event's eventArgs. This would be your only option if you wanted to modify the child control in codebehind.

However, because you are doing this from javascript and (ostensibly) want this autocomplete function to run on every single textbox, just give the table row a class and target the rendered input tag inside of it:

.aspx:

<itemtemplate>
      <tr>
         <td>
          <asp:RadioButtonList runat="server"  DataSource="<%#         ((Outlet)Container.DataItem).OutletInformations %>" DataValueField="DateOfDelivery" DataTextField="DateOfDelivery" />        
         </td>
         <td class="autocomplete">
            <asp:TextBox ID="ContactID" runat="server"/>
         </td>
      </tr>
   </itemtemplate>

JS:

<script type="text/javascript" >
    function OnContactSelected(source, eventArgs) {
      var fields = document.querySelectorAll(".autocomplete input");
      for(var i = 0; i < fields.length; i++){
        fields[i].value = eventArgs.get_value();
      }
    }
</script>

Upvotes: 1

Related Questions