Reputation: 37
I'm attempting to change a label inside a repeater in real time based on the value of a textbox that is also inside the repeater.
I have tried using JS to solve this but can not access the label nor the textbox inside the repeater.
I have no problem accessing the label or textbox if it's outside the repeater
JS:
<script language="javascript" type="text/javascript">
document.getElementById('<%=labelToUpdate.ClientID%>').innerHTML = document.getElementById('<%=txtInput.ClientID%>').value;
</script>
ASPX:
<asp:TextBox ID="txtInput" runat="server" class="form-control"></asp:TextBox>
<asp:Label ID="labelToUpdate" runat="server"></asp:Label>
Any help always appreciated.
Thank you
Upvotes: 1
Views: 1049
Reputation: 9460
asp:repeater
adds its id
(and its parent id
s) before item level control id
s. So use this idea. Place script after the repeater.
<script>
//language="javascript" is deprecated
//type="text/javascript" is default and cam be omitted
var txts = document.querySelectorAll('input[id$=txtInput]');
for(var i = 0, txt; txt = txts[i]; ++i){
txt.addEventListener('change', function(){
document.getElementById(this.id.replace('txtInput', 'labelToUpdate')).innerHTML = this.value;
});
}
</script>
You can also use jQuery if it is easier.
Upvotes: 1
Reputation: 35514
Repeater controls are inside the ItemTemplate, so you cannot reference them directly. You need to access them by an index.
With your method you could do this
document.getElementById('<%= Repeater1.Items[i].FindControl("labelTotalCsrPercentage").ClientID %>').innerHTML =
document.getElementById('<%= Repeater1.Items[i].FindControl("txtInput").ClientID %>').value;
Or it becomes easier when using jquery. You can then use nth-of-type
selector
$('#MyRepeater1 span:nth-of-type(2)').html($('#MyRepeater1 span:nth-of-type(2)').prev('input').val());
For this you need to wrap the Repeater with an element with a unique ID
<span id="MyRepeater1">
<asp:Repeater ID="Repeater1" runat="server">
</asp:Repeater>
</span>
Upvotes: 1