0

I have an ASP .NET page which contains dynamically created user controls (all instances of a single control) inside several repeaters. Each of these user controls contains, amongst other things, a text box which I want to blank out using an HTML button below it. As I don't want to cause any postbacks I'm attempting to do this all client-side using jQuery.

On the main page I have the following:

var removeCommentBtns = $('.remove-comment-btn');
for (let i = 0; i < removeCommentBtns.length; i++) {
    if (removeCommentBtns.val() != null) {
        removeCommentBtns[i].addEventListener("click", function () {
            //blank out text box
        })
    }
};

This loops through all the buttons I want to add the text box clear event to, but I have had no luck working out what I need to put in the event listener to blank out the text box. I can't refer to the text box using $('#<%=txtTextBox.ClientID %>') because the text box lives in my user control.

I've also tried various DOM manipulation things, such as finding the previous span where the text box is and setting the textContent $(this).prevAll('.span-clause-comment')[0].textContent = ""; but this causes the text box itself to disappear too.

I'm sure there is something fundamental that I'm missing!

Wooderson
  • 13
  • 4

2 Answers2

0

I think this can solve your problem of accessing dynamically created elements. Access dynamically created items using jQuery?

But I prefer to use vanilla javascript. So I suggest you to use event delegation which you need to access the nearest parent element that is already exists on page load and then access any dynamically created child elements using event.target.

Muhammed
  • 96
  • 3
  • 8
  • Thanks for the response, but I don't see how that would help me? I have no problem firing events from the buttons that are created, my issue is how to target `` in the child control from the parent page. – Wooderson Aug 05 '20 at 13:18
0

I finally figured this out. I was able to blank out (or set) the text in the text box by locating the closest div and then finding the text box using wildcards.

var txt = $(this).closest("div").find("[id*=txtTextBox]");
txt[0].textContent = "";
Wooderson
  • 13
  • 4