Tips for retrieving the label value within a repeater control and storing it in a JavaScript variable

I need help extracting the label value from a repeater control and storing it in a JavaScript variable

<asp:Repeater ID="rep_tskAttachments" runat="server" OnItemDataBound="rep_tskAttachments_ItemDataBound">
        <asp:Label ID="rlbl_Remarks" runat="server" Text='<%# Eval("REMARKS") %>'></asp:Label>     
 </asp:Repeater>

This is what I have tried so far

var valComments =document.getElementById('<%=rlbl_Remarks.ClientID%>').innerText;

Answer №1

One issue is that the repeater may have varying amounts of "sets."

Here's one way to handle it:

        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <asp:Label ID="lblHotel" runat="server" 
                    width="200px"
                    Text='<%# Eval("HotelName") %>' >
                </asp:Label>

                <asp:Button ID="Button1" runat="server" Text="Row click (client side)"
                    OnClientClick='<%# "myrowfun(" + Container.ItemIndex.ToString + ");return false;" %>'
                    
                    />

                <br />
            </ItemTemplate>
        </asp:Repeater>

        <script>
            function myrowfun(ix) {
                alert("row click index = " + ix)
                lblID = "Repeater1_lblHotel_" + ix
                alert(lblID)
                
                alert("Hotel name from repeater = " + $('#' + lblID).text())
                
                MyLabel = document.getElementById(lblID)
                alert("Hotel = " +  MyLabel.innerText)
            }
        </script>

To populate the repeater, we can do this:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        LoadGrid()
    End If
End Sub

Sub LoadGrid()

    Using con As New SqlConnection(My.Settings.TEST3)
        Using cmdSQL =
            New SqlCommand("SELECT TOP 5 ID, FirstName, LastName, HotelName from tblHotels ORDER BY HotelName", con)

            con.Open()
            Repeater1.DataSource = cmdSQL.ExecuteReader
            Repeater1.DataBind()

        End Using
    End Using

End Sub

With this setup, you'll see something like this:

https://i.sstatic.net/CAoLw.png

When you click on a row, it triggers the JavaScript function and retrieves the corresponding hotel value.

For example:

https://i.sstatic.net/N5dO3.png

Even with only one set in the repeater, the index will start at 0, and each label will follow the naming convention:

"repeater name" + "_" + "label name" + "_" + row index

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on updating route and content dynamically without triggering a page reload while ensuring search engine indexing compatibility

I am curious to find a way to change the URL displayed and have it reflect different content on the page, all while ensuring that it is search engine friendly for indexing by robots. I have experimented with using AJAX for dynamic data loading and angular ...

What is the best way to extract a specific year and month from a date in a datatable using

My dataset includes performance scores of employees across various construction sites. For instance, on 2020-03-15, ALI TAHIRI was at the IHJAMN site. I need to filter this dataset by year and month. If I input 2020 for the year and 03 for the month, the d ...

Jump to Anchor when Page Reloads

Hey there! I'm currently developing a gallery script and I'm trying to figure out how to automatically position the page to the top of a specific anchor when it is loaded. I attempted to use the following code: <script>location.href = "#tr ...

Utilize AJAX to dynamically populate a list in CodeIgniter

Currently, I am working on a project that involves using Codeigniter. One of my tasks is to populate a dropdown list from the database using Ajax. However, I encountered an error: "Uncaught SyntaxError: missing ) after argument list." Below is the code sn ...

Adding Material-UI icons dynamically in a React TypeScript project requires understanding the integration of imported icons

I have a collection of menu buttons with icons, stored in an array of objects. The icon names are saved as strings that correspond to Material UI icons: interface MenuButton { text: string, onClickFunction: Function icon: string } export defau ...

Tips for generating a JSON string with nested structure

Can someone assist me in generating a JSON based on the HTML elements provided below? { "AppName": "ERP", "ModuleDesc": [ { "Name": "Payroll", "AcCESSRIGHTS": [ { "Create": "Y", "Retrive": "Y", "U ...

Navigating to a Different Page in React Based on Button Click and Meeting Specific Conditions

Within this particular component, I have implemented a button named Submit. When this button is clicked, it triggers a series of actions: first, it exports the drawing created by the user as a jpeg URL, then sends this image data to another API that genera ...

Developing a side panel for navigation

My goal is to create a sidebar that shifts to the right from the left side and makes space on the page when the hamburger menu is pressed. I have made progress in achieving this, but I am encountering difficulties with the animation. const btnToggleSide ...

Collapse dropdown menus upon clicking outside of them

As a newcomer to coding, I'm trying to figure out how to create multiple dropdown menus where each one collapses when you click outside of it. I've been struggling with the code I wrote for weeks now - I want to have 3 dropdown menus but only one ...

Looking to showcase more detailed items within ng-repeat in AngularJS

Retrieve an object from the server that resembles the following structure: "courses": [ { "id": 1, "name": "piano", "classes": [ { "id": 1, "name": "piano1", }, { ...

Unexpected behavior exhibited by DOM elements

I can't seem to figure out this issue. Every time I run this loop: for ( var i=0; i < 10; i++ ) { var $items = $(balls()); console.log($items); $container.imagesLoaded(function(){ $container.append( $items ).masonry( 'app ...

What could be causing the issue with HTML not being printed upon button click in ReactJS?

My goal is to display the word "Hello" on the screen when the add button is clicked. However, I am encountering an issue where it is not showing up. Any insights or solutions would be greatly appreciated! import React, { Component } from 'react'; ...

Dropdown functionality in JavaScript and Bootstrap

Struggling with getting the bootstrap dropdown to change class on click? Don't worry, I've managed to make it change from "+" to "-", but now I'm facing an issue. When I click on the second dropdown, the one I clicked before doesn't cha ...

How can one safeguard their JavaScript code from potential threats and unauthorized access?

How can I ensure that a web app is not accessible or operated from the local file system? The app has a custom front-end workspace created with JS and various libraries, which should only be usable when the user is logged in to the domain with an active i ...

ExpressJS subclasses are failing to inherit attributes and properties in callback functions

Currently, I am utilizing ExpressJS 4.16 on Node v8.9.4 and have established a base controller to manage default routes with the following example: class BaseController { constructor(name, app, router, data) { this._name = name; this._app = app; ...

Retrieve the next 14 days starting from the current date by utilizing Moment.js

Looking to display the next 14 days in a React Native app starting from today's date. For example, if today is Friday the 26th, the list of days should be: 26 - today 27 - Saturday 28 - Sunday 01 - Monday 02 - Tuesday ............ 12 - Friday Is ther ...

JavaScript date input formatting with HTML

When using the input date picker in HTML, the default format displayed is MM-DD-YYYY. <input type="date" id="gdatum" /> Is there any method to change the mask to DD-MM-YYYY? ...

What is the best way to achieve the functionality of this ajax jquery using vanilla JavaScript?

I am attempting to replicate this jQuery ajax POST request in Vanilla JS, which currently looks like: $.ajax({ method: 'POST', url: window.location.href + 'email', data: { toEmail: to, fromName: from, ...

Unexpected CultureNotFoundException encountered in an ASP.NET Core API Controller

Extracted from the Azure App Service event log, this error seems to be related to using Localizated Int.Parse(string, CultureInfo) due to dealing with multiple cultures. Any suggestions on how to resolve this issue? EventId: 2 RequestId: 8004d77f-0000-f1 ...

Button event causes the list to become empty

I am facing an issue where every time the button event is fired, my list gets cleared and starts adding items from the first index. The old items added on previous clicks are not retained. I am trying to store IDs of some elements in my list on every butto ...