Amir
Amir

Reputation: 685

How to add datePicker by class dynamically using jquery?

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. :)

Upvotes: 0

Views: 1208

Answers (2)

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

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
          }
    });
});

Upvotes: 3

Bryan Zwicker
Bryan Zwicker

Reputation: 652

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/

Upvotes: 0

Related Questions