+ Reply to Thread
Results 1 to 2 of 2

Thread: Can't remove added fields with JQuery

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    30

    Can't remove added fields with JQuery

    I'm using JQuery to let users dynamically add & remove form fields, but it's not working properly. I can't see why this code shouldn't work but it doesn't..

    It works fine removing the first field (which is "hard-coded" in the HTML), but it won't remove the fields that's been added dynamically..

    here's the JQuery code
    Code:
      $("#addDog").click(
        function(event) {
          event.preventDefault();
          var doglist = <?php echo "'" . $javadogs . "'"; ?>;
          var newdog = '<div><select name="resDog[]" class="select">' + doglist + '</select> <input type="text" class="shortinput" name="resResult[]" size="20" value="" /> <a href="#" class="deleteDog"><img src="/admin/images/delete.png" alt="Ta bort hund" /></a></div>';
          $(this).parent().before(newdog);
        });
      $(".deleteDog").click(
        function(event) {
          event.preventDefault();
          $(this).parent().remove();
        });
    I've seen answers to similar questions using JQuery's live() function, but it's been deprecated since JQuery 1.7, so I can't use that...
    Tried using on() but that didn't work either =/

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    35
    here is the fix .
    Code:
    $(document).on("click", ".deleteDog", function(e) {
        e.preventDefault();
        $(this).parent().remove();
    });
    all of these deleteDog buttons will be housed in some sort of container. If all of these buttons were to be in a div with an id of foo, you would more efficiently set up the events like this:
    Code:
    $("#foo").on("click", ".deleteDog", function(e) {
        e.preventDefault();
        $(this).parent().remove();
    });
    Now, instead of every click anywhere in the document being inspected, only those clicks that bubble up to #foo are.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts