Search code examples
javascriptjqueryhtmlfunctionanytime

How do I dynamically assign IDs to form fields with event listeners?


I am allowing for the user to click a link, which will add a field to the page. The user can click the link to add as many fields to the page as they like. When the field is clicked, a calendar appears, because it is a date field. I am using the Any+Time calendar. The jQuery waits for a click event from the field with a specific id. Here is the code:

$('#start_date').click(
        function(e) {
            $('#start_date').AnyTime_noPicker().AnyTime_picker().focus();
        } );

The id is start_date. The problem is that the user can click the link to add a new field called start_date and since the id is the same, the jQuery event listener cannot uniquely identify each field. Is there a known solution for this kind of a scenario?


Solution

  • I'm not clear: does appending the unique number not work for you? If you're OK creating the field but it's not attaching the click handlers, then try adding a class="pickerField" to the elements when you create them, and change your handler to:

    $('.pickerField').click(
            function(e) {
                $(this).AnyTime_noPicker().AnyTime_picker().focus();
            } );
    

    I believe that should work with jQuery 1.7.2. If for some reason it doesn't, then try the following instead:

    $('.pickerField').on('click',
            function(e) {
                $(this).AnyTime_noPicker().AnyTime_picker().focus();
            } );
    

    If you're using an older version of jQuery, try using live instead of on.