0

I've been using jquery to trigger events on dynamically generated text fields using on, delegate and alike, just as described in this answer. That works very well, but when I try to add another dynamically generated layer, I can't get the action to trigger. So for example

Dynamically adding people to a list is fine

| People List
|
| 1) Name _______
|
|  ---------------------
| |Click to add a person|
|  ---------------------
|

If I want to dynamically add people to a list and trigger an alert each time the focus is on the text box the following works fine for that

$('div.people-list').delegate('input.name', 'focusin', function(){
  alert("textbox focusedin");
});

The Problem Comes when I have a list of lists. So say I wanted to have a dynamic list of multiple buses with a dynamic list of multiple passengers. Something like below.

| Bus List
|
|  1)  Bus ID_______
|   
|   | Passenger List
|   |
|   | 1) Name _______
|   |
|   |  ---------------------
|   | |Click to Add a Person|
|   |  ---------------------
|
|  ------------------
| |Click to Add a Bus|
|  ------------------

Under those circumstances, it seems that my above javascript using delegate is not sufficient. What do I need to add to trigger events on this sort of nesting?

In the even that it matters (though I don't think it would), I'm using rails and the cocoon gem for the field dynamics.

Community
  • 1
  • 1
neanderslob
  • 2,633
  • 6
  • 40
  • 82
  • 1
    Use `$(document).delegate` and try!! and add relevant code regarding how you are adding dynamic controls!! – Guruprasad J Rao Jun 23 '15 at 13:58
  • @GuruprasadRao Sorry for the delay. As you probably expected, your solution worked perfectly. Feel free to write up your comment as an answer so I can properly credit you. Thanks! – neanderslob Jun 24 '15 at 21:30

1 Answers1

1

Since you are dynamically adding controls it will be good if you refer them with document to delegate to them. So you can try below code.

$(document).delegate('input.name', 'focusin', function(){
  alert("textbox focusedin");
});
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200