0

Function doesnot get attached with newly created input box. Please check my code on this link

[Please check this code][1]

$("#datepicker").datepicker();


$("button").click(function(){
  
  $(".add").html('<input id="datepicker" placeholder="click here to open calendar " type="text" />');
  

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='add'><input id="datepicker" placeholder="click here to open calendar " type="text" /></div>
<button>Add input again </button>

depen.io/anon/pen/adLzi

1
  • 2
    Please include the relevant (MCVE)code here, in your question. Don't expect people to follow links around the internet in order to help. Commented Sep 30, 2014 at 10:06

4 Answers 4

1

When you are clicking on the button, this is the code which is being executed :

$("button").click(function(){
    $(".add").html('<input id="datepicker" placeholder="click here to open calendar " type="text"   />');
});

What this does is that is replaces the datepicker with a new one. Nothing wrong except that the event attached has a problem reattaching it.

TL:DR, use this code :

$("button").click(function(){
   var el = $('#datepicker');
  $.datepicker._clearDate(el);
});

Edit

Even I don't know the exact reasons why this happens but this is probably because internally, jquery UI has no link of the previous DOM element and it is left hanging. This also leads to memory leaks.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

$("button").click(function(){
  $("#datepicker").val("");
  $("#datepicker").focus();
});

Demo

Comments

0
$("button").click(function(){

   $(".add").html('<input id="datepicker" placeholder="click here to open calendar " type="text" />');

   // move to here your cod
   $("#datepicker").datepicker();

});

$(".add").html(...) means delete and create new DOM object

then lost meaning $("#datepicker").datepicker();

2 Comments

I have to replace content.Not append.
Thats ok..but why This function is not getting attached with InputBox we added using javascript?
0

Try to move the plugin init into your document.ready function:

$(document).ready(function() {
$("#datepicker").datepicker();`
});

$("button").click(function(){
  
  $(".add").html('<input id="datepicker" placeholder="click here to open calendar " type="text" />');
  

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='add'><input id="datepicker" placeholder="click here to open calendar " type="text" /></div>
<button>Add input again </button>

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.