You are viewing limited content. For full access, please sign in.

Question

Question

Button in Custom HTML within a Collection

asked on September 13, 2017

Hi, I am currently doing some development in Forms where I have created a button using custom HTML within a collection. For testing purpose, the button simply display an alert message with the button ID when pressed. I have the following code:

<button id="start1" type="button">Alert</button>

$("button").click(function() {
    alert(this.id);
});

This works for the first button in the first set of collection, however when adding the second set or the third set of collection, the button in the second set or the first has no response when pressed. The first button remains functional. Does anyone have any idea or can someone point me in the right direction to get this working? Thanks.

0 0

Answer

SELECTED ANSWER
replied on September 13, 2017

The problem you're probably encountering is that adding items to a collection after the form is loaded will create new elements in the DOM tree, which will not have any of the custom event handlers you attached on load.

You'll probably need to re-bind the event handlers each time items are added to the collection (you could use a function attached to the click event of the "Add" link). Another problem you'll encounter is that they would all have the same ID since it would just clone the custom HTML.

Instead of hard-coding the ID, I would add a custom CSS class to your custom HTML element. For example, "alertBtn"

Then on document ready, and each time the "Add" but is clicked, do the following:

$('.alertBtn button').each(function(index,value){
    // set the ID based on the index as it loops through each item
    $(value).attr('id','start' + (index + 1));
   
    $(value).click(
        //assign your click event function here
    );
});

 

0 0
replied on September 13, 2017

Brilliant! That works perfectly, thanks!

0 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.