1

According to the other stackoverflow posts on this, this should work. Yet it doesn't really. This is the code. Pretty basic just for testing.

HTML:

    <form>
        <div id="inputs">
            <p><input type="text" id="user" /></p>

        </div>
        <hr />
        <input type="button" value="Add Another Row" class="add" id="add" >
    </form>

And JQuery:

<script>
  $(function() {
    var node = "";
    var count = 0;

    $('#add').on('click', function() {
    $node = '<p><input type="text" id="' + count + '"><a href="#" class="remove">Remove Number' + count + '</a></p>';
    count++;
    $('#inputs').append(node);
  });

  $('.remove').on('click', function() {
    $(this).parent().remove();
    return false;
    });
  });

 </script>

What's weird is that the Add Field function works on my browser. Yet I put the same code into JSFiddle and it wouldn't work there. The remove function doesn't work at all, either in my browser or in JSFiddle. I'm still learning JQuery and Javascript in general, so any assistance in helping me learn would be much appreciated. Thanks!

George
  • 123
  • 1
  • 1
  • 8

1 Answers1

3

First problem with your code is usage of a wrong Variable

You have declared var node = "";

But assigning it to $node = '<p><input

And appending it to $('#inputs').append(node);

node is always empty .. But $node contains the HTML

Secondly you need to delegate the event

$('.remove').on('click', function() {

supposed to be

$('#inputs').on('click', '.remove',  function() {

Events will be only bound to the elements, that exist on the page at the time when the evnent is attached.

So delegating the event should solve the problem.

Check Fiddle

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • Excellent! Thank you Sushanth. Should I look up more information on this under the topic "delegation"? Or is it called something else? – George Jun 17 '13 at 23:43
  • @George - look for "event delegation". It's really very simple: you can listen for an event not only on a specific element, but on any parent of that element. jQuery's `.on()` method lets you do that and combine it with a check for the specific elements you want. Sushanth's code attaches the event listener to the `#inputs` element, and jQuery checks to see if the event actually occured on a `.remove` child of that element. If it did, it calls *your* event listener function. – Michael Geary Jun 17 '13 at 23:46
  • Michael and Sushanth - You both rock! Thanks for the help and explanation. I'm going to go look up more information so I don't make this mistake again :) – George Jun 17 '13 at 23:52