Search code examples
javascriptcocoon-gem

Selecting elements of dynamically added form


I have a Rails form dynamically generated by Cocoon gem. I start page with one element, but most likely will add much more.

Unfortunately, jquery selector which should apply on them, does not work.

The selector is as follows:

$(document.body).on("click", "#datepicker",       function() {
    $( "#datepicker" ).datepicker({
    });
});

My aim is to open datepicker when input fields with id datepicker are being clicked on.

Funny thing, the first form on the page would show datepicker if I click the field, then click elsewhere, then click the field again.


Solution

  • id is the HTML attribute to define the id-entity, or, in plain English, the identity of an HTML tag. Since it is nonsense to have two tags with the very same identity, id is expected to be unique. That is so much the case that an HTML which contains duplicated ids is considered to be invalid.

    So, your selector tells jquery that the identity with a given id should be searched for. jquery on the other hand will search for that identity and will stop its search when the first corresponding tag is found. The reason of this is that it is pointless to continue the search for a unique identity if it was already found. So, the selector will find the very first tag having that id and will do whatever needs to be done for it.

    Other answers suggested that you should use a class. The logic behind that is that the class is effectively a classification, so its findings share a common pattern of classification, which means that when the first such tag is found, the search will be continued. This is a clever idea, but it is not the only solution. To put it into more general terms: you need to have valid html and a selector which does not assume that the finding is unique.

    You can do that with ids sharing a pattern if you really prefer the usage of id in this case. Notice that the solution of the example did not contain a hashtag.

    Also, it is not a good idea to initialize a datepicker each time a click is issued on a given tag. You should do it only once per tag.