AMal lal AMal lal -3 years ago 160
HTML Question

Get the element after appending using Jquery or Javascript

I have a

<div>
.I am trying to append another which contains a inside.I am trying to call the input tag by id, but am not getting this element! I tried many questions in the stack, but I can't solve this.

Here is the HTML code

<div id="newContDiv" class="form-group">
<div id="newDiv"></div>
</div>


jquery for appending div and input tag

var v = "<div id = 'coverDiv'><div id='appDiv'><div><input id='panNumId'
type='text' name='panImg1' placeholder='Enter your Pancard number'/>
</div></div>";
$('#newDiv').append(v);


And I am calling the element as

$('#panNumId').click(function () {
alert("clicked");
});

Answer Source

Since your element is dynamically appended, you wont be able to handle a click event like you are doing. You will need to update your click event to:

$("#newDiv").on("click", "#panNumId", function(){
    // code goes here
});

Like this

$(function() {
  var v = "<div id = 'coverDiv'><div id='appDiv'><div><input id='panNumId' type = 'text'name = 'panImg1'placeholder = 'Enter your Pancard number' / ></div></div > ";
  $('#newDiv').append(v);

  // it will alert the moment you click the textfield
  $('#newDiv').on("click", "#panNumId", function() {
    alert("clicked");
  });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="newContDiv" class="form-group">
  <div id="newDiv"></div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download