Obtain the text content of a span within a repeater using JavaScript or jQuery

I am facing an issue with retrieving the value of a span (or label) from my HTML code. Here is the snippet:

<asp:Repeater ID="rpt_district" runat="server" >
            <ItemTemplate>
            <tbody id='bodies'>

                <tr>
                <td>
                    <span id="district_id"><%# Eval("DISTRICT_ID") %></span>
                </td>
                <td><%# Eval("DISTRICT_NAME") %></td>
                <td>
                    <asp:Label ID="lb_city_id" runat="server" Text='<%# Eval("CITY_ID") %>'></asp:Label>
                </td>
                <td style="float:left; margin-left:5px;">
                    <asp:CheckBox ID="cb_status" runat="server" onclick="javascript: return false;" />
                    <asp:HiddenField ID="hf_status" Value='<%# Eval("ENABLE") %>' runat="server" />
                </td>
                <td>
                    <div style="float:left; margin-left:4px;" >
                        <asp:ImageButton ID="ib_edit" runat="server" ImageUrl="~/Hinh/icons/Edit.png" ToolTip="Edit" />
                    </div>
                    <div style="float:left; margin-left:4px;">
                        <asp:ImageButton ID="ib_delete" runat="server" ImageUrl="~/Hinh/icons/Trash.png" 
                                        ToolTip="Delete" CommandArgument='<%# Eval("DISTRICT_ID") %>'
                                        OnClientClick="getvalue(); return false;"/>

                    </div>
                </td>
                </tr>


            </tbody>
            </ItemTemplate>
            </asp:Repeater>

I need to extract the value of district_id in the span tag (or label) using JavaScript when clicking on the image button.

function getvalue() {
    var thisspan = $('.district_id').eq(0);
    alert(thisspan);
}

However, I am only able to retrieve the value in the first column because of eq(0). I aim to achieve this using JavaScript or jQuery and not through code-behind. Thank you for your assistance.

Answer №1

According to HTML rules, each element must have a unique ID. The repeater in your code is generating elements with duplicate IDs. To fix this issue, modify the selector in your JavaScript from an ID to a class name using jQuery. Update the corresponding class in your HTML as well.

Answer №2

You are trying to find a specific class, but you possess an identifier instead.

let targetClass = $('#district_id').eq(0);

Answer №3

When selecting elements in HTML, classes are denoted by "." while ids are denoted by "#". Since your HTML uses an id, the code should be adjusted accordingly:

var thisspan = $('#district_id').eq(0);

It's important to note that ids are unique in HTML, so using .eq(0) is not necessary:

var thisspan = $('#district_id');

To retrieve the text value within the span element, you can use the following:

var thisspan = $('#district_id').html();

or

var thisspan = $('#district_id').text();

Answer №4

To add a CSS class to your image button, you can follow these steps. It's important to ensure that no two elements in the Document Object Model (DOM) have the same ID.

<asp:ImageButton ID="ib_delete" CssClass="imgClass" ..../>

If you want to retrieve the value of the first instance of the image button, you can use the following code snippet:

console.log($('.imgClass').val());

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

org.openqa.selenium.WebDriverException: unexpected issue: Chrome failed to initiate: crashed.(chrome inaccessible)

Having issues running Java script (selenium framework) on Chrome. Tried various solutions but still facing problems: Unchecked run as admin Added arguments Snippet of the code: ChromeOptions options = new ChromeOptions(); //options.setExperimentalOption ...

I'm having trouble extracting data into my HTML file using the append function in Jquery. What could be causing this issue?

Hey there, I'm having some trouble extracting data from a URL to my HTML file using jQuery. Can anyone help out? I'm still new to this. Here's the code <html> <head> <title> My Program </title> <script src="ht ...

Development of multiple interactive 3D models for the website

I have created a stunning 3D model of a city featuring 4 unique buildings, and now I want to take it to the next level by making them interactive. My vision is for users to hover over a building and see text appear on top of it, with the option to click an ...

Can CSS be used to generate these shadows?

Check out this image I made showcasing a board with an elongated shadow cast behind it. The intention is to emulate the look of the board leaning against a wall, resulting in a triangular shadow on either side. I'm curious if it's achievable to ...

Using jQuery's toggleClass method to implement CSS transformations

I have a question about this situation Each time the button is clicked, jQuery toggles the class: .transition { background-color: #CBA; transform: translateX(100px) scale(0.5) rotate(180deg); } Within the <div class="container2"> And upon ...

Continuing to fine-tune the regular expression for password validation

How can we refine this regular expression to only include alphanumeric characters? I assumed that by requiring at least 2 uppercase letters, lowercase letters, and digits, the expression would limit itself to those specific types of characters. Unfortunat ...

Using a PHP variable to trigger the jQuery .show() function

I'm attempting to trigger jQuery .show() events based on PHP variables. Below is my PHP code (retrieved from a form submission on another page): $last_pic_displayed = trim($_POST["last_pic_displayed"]); if (strlen($last_pic_displayed) <= ...

Troubleshooting Issue: ASP.NET UpdatePanel Not Responding to jQuery

I am having difficulties invoking jQuery functions within an "asp:UpdatePanel". Despite the code provided below, my attempts to add a class to the div element ".popup-body" are unsuccessful. Interestingly, the "alert();" function works without any issues. ...

JavaScript cannot determine the length of an array of objects

I'm encountering an issue with an array of objects named tagTagfilter. When I log it in the browser, it doesn't immediately show the correct length value inside. tagTagFilter: TagFilter = { filterName: 'Tag', tags: [] ...

Is there a solution or workaround for the issue of fake anti-aliasing in Microsoft Edge when it comes to the border of sticky headers using Bootstrap 4?

In my current project, I came across a Pen shared by Balaji731 on Bootstrap 4 table with the scrollable body and header fixed. While testing the Pen in Microsoft Edge, I noticed that when <th> borders are enabled, they disappear while scrolling, cre ...

What is the best way to conceal the broken image icon using PHP?

UPLOAD PICTURES IN DATABASE: if (!isset($_FILES['gambarid']['tmp_name'])) { echo ""; }else{ $rand5=rand(); $image_name5= addslashes($_FILES['gambarid']['name']); $fileext5=explode('.&ap ...

Developing an E-commerce Cart feature using AJAX, HTML5, and Jquery exclusively

I am looking to develop a Cart System using solely HTML5, AJAX, and Jquery without incorporating any server side scripting language like PHP or ASP.NET. The scenario I have is: "A designated HTML division displaying added products with their Name, Price, ...

Are the fetch functions within getStaticProps and getServerSideProps equivalent to the fetch API native to web browsers?

I've been working with Next.js for some time now and I'm questioning the fetch API used in both getStaticProps and getServerSideProps. Below is my understanding of these functions: getStaticProps runs during build time and ISR getServerSidePro ...

in JavaScript arrays, the identifier follows the numeric value right away

Can anyone assist me with assigning a PHP array of image filenames to a JavaScript array? I have made some progress, here's my code: <script src="jq.js"></script> <?php $dir = 'images'; $images = scandir($dir); $true_images ...

Issues with File Upload using Vue.js and the Flask framework

I am encountering difficulties when trying to upload an image using FormData from Vue.js to my Python Flask backend. In my setup, I have a Node.js server that is responsible for handling Vue.js (Nuxt) in order to enable server-side rendering. The basic sta ...

AJAX - Implementing a delay in displaying AJAX results

My search function uses AJAX to retrieve data from the web-server, and I am trying to implement a fade-in animation for each search result. I want the results to load and fade in one by one with a slight delay between them. Currently, it seems like all th ...

How can I position the close button correctly in a bootstrap popup modal?

I have a basic bootstrap popup modal. Currently, the close X button is centered within the popup window, but I would like to align it to the right corner instead. Is there a way to achieve this? <div class="modal fade" id="checkNameSurvey-modal" data ...

Jquery Tablesorter no longer supports the StickyHeaders widget

After encountering a similar issue as described in this question, I found myself facing a problem. My table includes a stickyHeaders widget that fixes the headers while scrolling. Additionally, there are checkboxes within some of the table cells. Upon chan ...

Centering the date vertically in JQuery Datepicker

I'm currently customizing the appearance of the jQuery datepicker, but I'm facing difficulty in aligning the dates vertically at the center. Here's the progress I've made so far: https://jsfiddle.net/L4vrkpmc/1/ Since the datepicker i ...

Trouble with the alignment of Bootstrap grid columns

I'm facing an issue with bootstrap and I just can't seem to figure out why my columns aren't displaying correctly. I've been trying for the past hour but it's not working as expected. <link href="https://stackpath.bootstrapcd ...