Jump to content
Larry Ullman's Book Forums
zibrnp

Jquery Append() Inputs And .datepicker()

Recommended Posts

Hello,

I have a problem with a form I created.
The form should load one row of fields (first name, last name and Date).
When someone clicks on Date then jQuery date picker should display calendar.
Until this point everything works perfectly ok.

I also have a button that adds another row of the same fields (first name, last name and Date). The button adding new row works ok but calendar from jQuery date picker is not working in that newly added field.

Can you guys take a look what might be wrong with my code please…

Thanks, T

    $(document).ready(function(){

        var x=0;

            $("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});

            $("#add").click(function(){

                x++;
                $("#name_data").append('<p>First Name: <input name="name['+x+'][first]" type="text"> Last Name: <input name="name['+x+'][last]" type="text"> Date: <input id="datepicker" name="name['+x+'][date]" type="text"> <input id="remove'+x+'" type="button" name="remove" value="remove"></p>');

                $("#remove"+x).click(function(){
    
                    $(this).parent('p').remove();
                });
            });
    });
        <form action="test.php" method="post">
            <div id="name_data">
                <p>First Name: <input name="name[0][first]" type="text">
                   Last Name: <input name="name[0][last]" type="text">
                   Date: <input id="datepicker" name="name[0][date]"></p>
            </div>
            <p><input id="add" type="button" name="add" value="Add more"></p>
            <p><input type="submit" name="submit" value="Submit..."></p>
        </form>

Share this post


Link to post
Share on other sites

Your problem is occurring because your append method call is destroying the old datepicker input element and adding a new one to the DOM, but the datepicker method call is (likely) setting up a click event handler for the old input, which is no longer in the DOM.

 

Try adding the following line below the append method call (as well as retaining the call you already have):

$("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
  • Upvote 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...