0

I have form with single text input to which I want to add functionality - on click generate new text input. Here's my code:

HTML

<form>
   Fill:
   <input type="text" name="0" class="target"/>
   <br /><br /><br /><input type="submit" value="post it!" />
</form>

JS/jQuery

<script>
   var i=1;
   $(function(){
     $("input.target:last").on("click", function(){
      $("input.target:last").after("<br /> <input type='text' " +  "name='" + i +"'"  + ' class="target" />');
      i++;
      });
   });
</script>

This works fine but only when clicking on first (non-dynamically) generated input. I've checked in Firebug, generated inputs are just fine - they are generated with correct class name and name attribute are incremented as expected - everything fine except click event is not related to any input but the first one, non- dynamically generated.

mplungjan
  • 134,906
  • 25
  • 152
  • 209
Miloš Đakonović
  • 3,241
  • 4
  • 29
  • 48
  • From the [documentation](http://api.jquery.com/on/) (in bold): *"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to `.on()`."* – Felix Kling Jul 08 '13 at 08:32
  • @Dominic: `:last` is not a class, it's a pseudo selector. http://api.jquery.com/last-selector/ – Felix Kling Jul 08 '13 at 08:36

1 Answers1

1

Use delegated event handler:

 $(function(){
    $("form").on("click","input.target:last", function(){
      $(this).after("<br /> <input type='text' " +  "name='" + i +"'"  + ' class="target" />');
         i++;
      });
   });

When the second parameter is a selector, the event handler is delegated. Documentation

Khanh TO
  • 46,783
  • 12
  • 97
  • 112