Nida
Nida

Reputation: 1702

<td> click not getting triggered

I have tried following lines of code like

                  $(".datepicker .day").click(function(){
                     var dob = $("#dobfield").val().trim();
                     var calculatedAge = GetAge(dob);

                    if(calculatedAge < 0)
                        $("#age").val("");

                    else if(!isNaN(calculatedAge))
                        $("#age").val(calculatedAge);
                 });

In html

          <div class="datepicker">
           ...
             <table>
              ...
               <tr>
                 ...
                   <td class="day"> 12</td> 

I am trying to add age dynamically to the textbox age. The .datepicker .day click event is not getting fired. Please help me !!!

Upvotes: 0

Views: 66

Answers (2)

H77
H77

Reputation: 5967

You can use the .on function to listen to the click event of dynamically added table cells by attaching it to the .datepicker div.

If the .datepicker div is generated dynamically you'll have to add the on function to the document itself.

e.g.

$(document).on("click", ".datepicker .day", function() {
  console.log("clicked");
});

// dynamically adding the datepicker.
$("#container").append("<div class='datepicker'><table><tr><td class='day'>12</td></tr></table></div>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>

Upvotes: 1

Manish
Manish

Reputation: 5066

Try this. It seems to work fine wrap your code in $(document).ready function. Below is demo of working code.

$(document).ready(function() {
  $(".datepicker .day").click(function() {
    var dob = $("#dobfield").val().trim();
    console.log(dob)
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="datepicker">

  <table>
    <tr>
      <td class="day"> 12 </td>
      <td><input id="dobfield" value="56" /></td>
    </tr>
  </table>
</div>

hope it helps :)

Upvotes: 1

Related Questions