Results 1 to 3 of 3

Thread: [RESOLVED] JQuery - Removing list-item

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    Resolved [RESOLVED] JQuery - Removing list-item

    I'm having an issue removing the last list-item in an unordered list. Here is my code:
    Code:
    $('#frmDriver').submit(function(e) {
    	$("#ulDriver").append("<li>" + $("#firstName").val() + " " + $("#lastName").val() + " - <button class='delete'>Remove</button></li>" );
    	window.location = $('#dialogDriverClose').attr('href');
    	e.preventDefault();
    });
    $('.delete').click(function() {
    	$(this).closest('li').remove();
    });
    What I'm expecting is for it to add the following code to an unordered list:
    Code:
    <li>firstName lastName <button class="delete">Remove</button></li>
    And then when I click on the remove button it should remove the list item that the button resides with, but what is happening is that it is creating the list item and button but whenever I click on the button nothing happens. Whenever I setup a breakpoint I notice that the lines never gets executed. What could be causing that?

    Also as a side note, I'd rather have an anchor instead of a button but whenever I replace the button with the anchor the hyperlink never comes up. Any ideas on that too?
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  2. #2
    PowerPoster kfcSmitty's Avatar
    Join Date
    May 2005
    Posts
    2,248

    Re: JQuery - Removing list-item

    How are you binding the click event of the button? If you're just doing something like
    Code:
    $('').click(function(e){});
    then that will not work on dynamically added elements. You would need to do something more like

    Code:
    $('body').on('click', '.remove', function(){
        alert('woozle');
    });
    As for the anchor not showing up, I would have to see how it is rendering and what your code looks like. You should be able to add an anchor tag without issue.

  3. #3

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,711

    Re: JQuery - Removing list-item

    That was exactly it, I changed the class name from remove to delete and it works perfectly.
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

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



Click Here to Expand Forum to Full Width