What is the best way to incorporate JavaScript in a repeater?

I am currently working on an asp.net project that involves using a repeater.

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
        <HeaderTemplate>
            <asp:label ID="lblexp" runat="server" Text="05/11/1981" Visible="false"></asp:label>
        </HeaderTemplate>
        <ItemTemplate>                
            <div id="myNest" class="grid">
            <div class="imgholder">
                <img src="<%# Eval("ImageAlt1")%>" />
            </div>        
            <strong><%# Eval("ItemName")%> <bdo style="color:green;">$<%# Eval("ItemPrice")%></bdo></strong>
            <p class="test"><%# Eval("ItemDescription")%></p>
            <div style="color:red; font-size:small;"><asp:Label ID="lblExp" Text='<%# Bind("CreateDate") %>' runat="server" /></div>
            <div class="meta"><%# Eval("Email")%></div>
            </div>
        </ItemTemplate>
        <FooterTemplate>
            <asp:label ID="lblexp" runat="server" Text="05/11/1981" Visible="false"></asp:label>
        </FooterTemplate>

Additionally, I have included a JavaScript function to truncate the ItemDescription text.

<script type="text/javascript">
    var after = 5;
    var html = $(".grid p.test").html();
    html = html.substring(0, after) + "<span> ...</span>";
    $(".grid p.test").html(html);
</script>

However, there seems to be an issue where the JavaScript cannot access the elements within the repeater. How can I resolve this issue?

Currently, the error message shown is Uncaught TypeError: Cannot read property substring of undefined

Answer â„–1

There are a couple of potential issues to address in this situation:

  1. One issue could be that the JavaScript is running before the relevant markup is fully rendered. To resolve this, ensure that your JavaScript is wrapped within a document load handler like so:

    $(function() {
        var after = 5;
        var html = $(".grid p.test").html();
        html = html.substring(0, after) + "<span> ...</span>";
        $(".grid p.test").html(html);
    });
    
  2. Another consideration is that the html() method retrieves the inner HTML of only the first matched element in the selector. If you need to manipulate all matched elements, utilize the each() function. Additionally, think about using the text() method instead of html() for a more appropriate solution in this case.

Answer â„–2

It seems like your script may be executing before the DOM is fully loaded. To ensure that your script runs after the DOM is ready, you can either move the script tag just above the closing </body> tag or wrap your script within a <script> tag like this:

<script type="text/javascript">
  $(function () { // equivalent to $(document).on('ready', function...
    var after = 5;
    var html = $(".grid p.test").html();
    html = html.substring(0, after) + "<span> ...</span>";
    $(".grid p.test").html(html);
  });
</script>

By passing a function to the jQuery $(function () { }) method, you can ensure that your logic will only execute after the DOM has finished loading, guaranteeing that your script will run only when the entire page is ready.

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

Creating a JSON object using various inputs through AngularJS

Just starting out with Ionic, Angular, and Firebase. This might be a silly question :) I'm working on an app using Ionic + Firebase, and I want to create a JSON object from multiple inputs. The interface looks like the image below: https://i.stack.i ...

Utilizing Array in ReactJS with the Power of Hooks

My current situation involves having an array of FooBar objects interface FooBar { foo: string, bar: string, correct: string, other: string[] } const [arrOfObj, setArrOfObj] = useState<FooBar[]>([ { "foo": "fool ...

"Duplicate content issue with ng-transclude causing element to render twice

Why is the transcluded directive displaying Name inside directive = Frank twice? I believed I had a good grasp on transclusion, but this specific scenario has left me puzzled. Check out this fiddle for more details <div ng-app="myApp" ng-controller=" ...

Transform various tables enclosed in separate div elements into sortable and filterable tables

I'm encountering an issue with making multiple tables sortable and searchable on one page. Despite all the tables having the same class and ID, only the first table is responsive to sorting and searching. I've followed a tutorial that recommends ...

Introducing the Generic DefaultWait for Webdriver

In my IDriver class, I am looking to implement a method like the following: this.driver.WaitUntil(x => LoginForm.Displayed, TimeSpan.FromSeconds(5)); this.Driver is an IDriver field The current implementation does not wait for element to be displayed ...

Navigating through the Document Object Model within a table

I'm working with an HTML table that contains a delete button in each row's last column. When the button is clicked, I want to delete the entire row. However, my current code only deletes the button itself and not the entire row: var buttons = do ...

Executing a NodeJS function from a JavaScript function

I am working on a project involving Firebase and I am looking to connect a server-side function that can send an email to the client-side script. Below is my server-side index.js file: const functions = require('firebase-functions'); var nodema ...

Ways to ensure the title changer works seamlessly for everyone

Having a title changer for elements visible in the viewport is crucial. However, the current setup only works for a single division and fails to function with multiple divisions. Click Here for Live Testing and Viewing Check out the jsFiddle for Code V ...

Submit a single data value to two separate models in JSON format using MongoDB

I recently developed a code with 2 essential functions: module.exports.registerAccount = (reqBody) => { let newAccount = new User({ firstName : reqBody.firstName, lastName : reqBody.lastName, email : reqBody.email, mobileNum : reqBody.m ...

At times, the animation in SetInterval may experience interruptions

I have created an animation using a sequence of images. The animation runs smoothly with the setinterval function, but for some reason, it occasionally pauses. I've shared a fiddle where you can see this pause happening. Click Here to See the Unwante ...

JavaScript for Office Spreadsheet Titles

I'm having trouble fetching the names of sheets from an external Excel file, as I keep getting an empty array. async function retrieveSheetNames() { const fileInput = <HTMLInputElement>document.getElementById("file"); const fileReader ...

Is there a way to integrate the distanceTo function from Leaflet into my own custom library that I am planning to develop?

I am currently incorporating leaflet into my project and I have encountered the distanceTo method which calculates the distance between two coordinates. My goal is to create a separate JS file with a function named getDistance() where I can house the logic ...

Ways to display a different div when clicking on a div?

Good afternoon, I've noticed that this question has been asked numerous times before, but none of the solutions provided seem to work for my specific issue. My problem involves a div with the class .title3. I want another div with the class .Content ...

Discovering the method to access a local function within a static function in Javascript ES6 (ES2015) or Typescript

Is there a way to access the non-static "foo2" method from inside the static "bar" method? So far, I'm only able to access the "foo1" and "foo3" methods. Can anyone provide guidance on how to achieve this? let foo1 = () => { alert('foo1†...

Empty canvas when Material UI Modal transitions states

I've been struggling to make a simple modal using material UI, but every time I try to change the state, it just shows a blank white page. Can anyone help me figure out why this is happening? Here's the code snippet: import {Button,Modal} fro ...

Having trouble accessing my API through localhost with NextJS

I'm currently working on an app that involves fetching data from my own API. The goal is to retrieve user-specific information and use it within the app. However, I've encountered a roadblock with CORS headers and I'm unsure of how to procee ...

Error 404 in Angular HTTP Request

I'm encountering a 404 error while attempting to send a post request, along with a 'possibly unhandled rejection' error. Given my limited experience with Angular, any advice would be greatly appreciated. I've gone through the documentat ...

Mastering Data Transfer in jQuery: A Guide to Migrating Event Information from .on(dragstart) to

I need help with transferring information between an .on(dragstart) event and an .on(drop) event. However, when I run the code below in Chrome, I encounter an error message: 'Uncaught TypeError: Cannot read property 'test' of undefined' ...

A guide on how to alternate between ng-hide and ng-show using separate controllers by utilizing a shared factory toggle state instance

Using Angular 1.x, I have implemented two controllers where I want to display controller_2 if controller_1 is hidden. To achieve this, I am utilizing a factory method. Here is the snippet of my HTML code:- <div ng-controller="controller_1 as c1" ng- ...

Navigating and exploring data stored in a mongoose database

Currently, I am attempting to filter data based on a specific id (bWYqm6-Oo) and dates between 2019-09-19 and 2019-09-22. The desired result should return the first three items from the database. However, my current query is returning an empty array. I wou ...