0

I am using "jquery-1.9.1.js" and my javascript code is as below:

$('.fromSearch').on('focus', function(){
var $this = $(this);
  if(!$this.data('datepicker')) {
   $this.removeClass("hasDatepicker");
   $this.datepicker();
   $this.datepicker("show");
  } 
});

my html code is this:

<div id="duration" class="duration">
    <td><input type="text" id="fromSearch" class="fromSearch"></td>
</div>

PROBLEM: I am generating "fromSearch" (date picker) dynamically, lets say 5 date pickers, but I get date picker only for the first time!

I have been working on solutions provided on similar questions, but none of them is working for me. Can any body help me figuring out where I am going wrong? Thanks for your time. :)

5
  • can you provide a demo fiddle so it will be easier to understand? Commented May 18, 2015 at 12:42
  • 4
    I would say you need to delegate event, e.g: $(document).on('focus', '.fromSearch', function(){...}); That's said, beware, IDs must be unique on document context. And BTW, your HTML markup is invalid Commented May 18, 2015 at 12:42
  • 2
    You need to use a delegated event handler as the .fromSearch element is added after the DOM has been loaded. Commented May 18, 2015 at 12:42
  • @A. Wolff, yes ids are unique for each of the dynamically generated text box. It goes like this fromSearch, fromSearch2, fromSearch3 ... fromSearch5 for each of the date pickers Commented May 18, 2015 at 12:44
  • @Amir Still be aware a TD cannot be direct descendant of DIV element Commented May 18, 2015 at 12:45

2 Answers 2

3

You can try as below:

$('body').on('focus', '.fromSearch', function(){
    $(this).datepicker();
});

UPDATE

To pass date to a function write onselect event in your datepicker as below:

$('body').on('focus', '.fromSearch', function(){
    $(this).datepicker({
          onSelect: function (dateText, inst) {
                   //do necessary actions
          }
    });
});
Sign up to request clarification or add additional context in comments.

5 Comments

Anytime.. Happy Coding.. :) Meanwhile you can mark it as answer if it helped.. :)
@Rao, now how can I send selected date to a javascript function?
@Amir.. Updated the answer. Check and let me know!!
Yessss it worked too, sorry I cannot double Tick here :D Thanks for your time :)
Anytime!! Happy Coding.. :)
0

Your code seems to work. You need to ensure you are including jQuery-ui. DatePicker does not come bundled with jQuery

http://code.jquery.com/ui/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.