0

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?

Jay
  • 558
  • 1
  • 7
  • 23
  • @thecodeparadox: Thank you for your answer. It didn't quite work. It worked for the *start\_date* field at first. Then when I clicked to add a new field, it did not show the calendar when I clicked the old *start\_date* field or the new one. The code is: `$('[id^=start_date_]').click( function(e) { $('[id^=start_date_]').AnyTime_noPicker().AnyTime_picker().focus(); } );` – Jay Jun 19 '12 at 11:23
  • What you can do is append a postfix number to the id like your dynamic control id will be start_date1,start_date2..., may be there is a better known solution for this. – MSUH Jun 19 '12 at 11:29
  • @MSUH: This is what I am doing. I have an iterator to append to the end of the *start\_date*. So they show as `start_date_0, start_date_1, etc` – Jay Jun 19 '12 at 11:32

1 Answers1

2

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.

Andrew M. Andrews III
  • 1,989
  • 18
  • 23
  • Note that you will still need to assign a unique ID to each field in order for it to work with Any+Time™ – Andrew M. Andrews III Jun 20 '12 at 03:09
  • Hi, I actually found the main problem which explained why the additional *start\_date* field wasn't responding to the click event. I was using `elmt.innerHTML += ` which was making the script unresponsive. Your solution unfortunately didn't work. The additional field was unresponsive. Using `[id^=start_date_]` makes the calendar show in the additional field when the initial field is clicked. I have redesigned my form so that I don't need to worry about this problem anymore. – Jay Jun 20 '12 at 16:50