Abhinab Kanrar
Abhinab Kanrar

Reputation: 1552

How to create datepicker on dynamiclly created textfield?

This is my textfield:

<input type='text' id='activationdate' name='activationdate' style='height:"+height*2.5/100+"px;font-size:"+height*2.3/100+"px' class='activationdate'/>

Dynamically created textfields will be like this:

<input type='text' id='activationdate"+temp+"' name='activationdate' style='height:"+height*2.5/100+"px;font-size:"+height*2.3/100+"px' class='activationdate'/>

temp is increased +1 wtih javascript each time a dynamic textbox is created and temp starts from 1

Now this is my jquery datepicker code:

$( document ).ready(function() {
    $('input[id^="activationdate"]').on('click', function() { 
    $(this).datepicker({
            changeMonth: true,
            changeYear: true
        });
    });
});

But it is not working. Please help..................

Upvotes: 0

Views: 51

Answers (1)

Satpal
Satpal

Reputation: 133403

You need to use Event Delegation using .on() delegated-events approach for dynamically created elements.

Use

$(document).on('click', 'input[id^="activationdate"]', function() {
    $(this).datepicker({
        changeMonth: true,
        changeYear: true
    });
});

EDIT

Apply plugin after creation of element instead of using event delgation

function addDataUpper(){
    //Your Existing code

    //Add Plugin
    $('#activationdate'+temp).datepicker({
        changeMonth: true,
        changeYear: true
    });     
    return false;        
}

Upvotes: 2

Related Questions