0

I am having a problem with the following; I have a dynamically generated table form. In one of the columns I have a select input with some options and in the following column I have an input field for Timestamp that should be automatically filled out with the current date as soon as the user selects one of the options. I have the following code, however, the timestamp is either only generated for the very first row (in case when I use id for input field) or for all of the rows (in case when I use class for input field). I would need the timestamp to be filled only in the same row as the select drop down list is. Any help would be greatly appreciated.

<select  class='Status'> 
  <option value= '1'> Option1 </option>
  <option value= '2'> Option2 </option>
</select> 

<input type=text class='TimeStamp'/>

Then for my JQuery I have the following code:

$(document).ready(function() {
    $('.Status').on('change', function() {
        $('.TimeStamp').val("CurrentDate");
});
});
Luke
  • 407
  • 2
  • 10
  • 22
  • 1
    HTML code with you table is more helpfull, or create jsfiddle – Nalin Aggarwal Sep 15 '16 at 17:28
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – vijayP Sep 15 '16 at 17:45

2 Answers2

1

You need to use event delegation like following.

$(document).on('change', '.Status', function() {
    $('.TimeStamp').val("CurrentDate");
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
1

Try this:

$(document).ready(function() {
    $('.Status').on('change', function() {
        // get current row
        var row = $(this).parent().parent();
        // find .TimeStanp in the current row and set value
        row.find('.TimeStamp').val("CurrentDate");         
    });
});
Ivnhal
  • 1,099
  • 1
  • 12
  • 20
  • Is there any easy way to format Date() that would return the date in this format: 09-14-2016 10:11:51 ? I tried the following code but it didn't work: `var d = new Date(); var h = d.getHours(); h = (h < 10) ? ("0" + h) : h ; var m = d.getMinutes(); m = (m < 10) ? ("0" + m) : m ; var s = d.getSeconds(); s = (s < 10) ? ("0" + s) : s ; datetext = datetext + " " + h + ":" + m + ":" + s;` – Luke Sep 16 '16 at 14:27
  • Take a look for [jQuery date formatting](http://stackoverflow.com/questions/5250244/jquery-date-formatting) – Ivnhal Sep 16 '16 at 18:17