treehouse : what would you like to learn today?
Web Design Web Development iOS Development

jQuery Append and then remove

  • Hello.

    I am using jQuery to append a list item when a box is checked and when it is unchecked I want that list item to go away. I got the first part to work, but not the second (removing portion). Here is a paired down version of my issue http://theschaafs.org/checked.html.

    I can't get down into the :not(:checked) portion of the code.

    Here is what I have thus far...


    <script type=\"text/javascript\">
    $(function() {
    $(\"form#explore input:checkbox\").change(function(e) {
    var title = $(this).attr(\"title\");
    if(\"input:checked\") {
    $(\"#search_by ul\").append(title).wrapInner($(\"<li class='\" + title + \"'></li>\"));
    } else if(\"input:not(:checked)\") {
    alert('Inside Else' + title);
    $('li.' + title).remove();
    }
    });
    });
    </script>


    Thanks for looking into it!
  • Few things to note,

    var title = $(this).attr("title");
    This will return <input type=checkbox title="title">

    And this is fine but you shouldn't be appending the title without wrapping....


    Also if("input:checked") is just a string
    "input:checked" != anything


           
    <script type=\"text/javascript\">
    $(function() {
    $(\"form#explore input:checkbox\").change(function(e) {
    var title = $(this).attr(\"title\"),
    item = '<li id=\" ' + title + ' \">' + title + '</li>';
    if( $(this).is(':checked\") ) {
    $(\"#search_by ul\").append(item);
    } else if( $(this).not(':checked\") ) {
    $('li#' + title).remove();
    }
    });
    });
    </script>



    So something like that .... that should get you on the right track
  • "Mr KiTT3N" said:
    Few things to note,

    var title = $(this).attr("title");
    This will return <input type=checkbox title="title">

    And this is fine but you shouldn't be appending the title without wrapping....



    What do you mean by without wrapping?

    I am trying to get the value of the title attribute...are you saying I am only looking for titles with the title of title? ;)

    Thanks Mr. KiTT3N!
  • How's this:
     <script type=\"text/javascript\">
    $(function() {
    $(\"form#explore input:checkbox\").change(function(e) {
    var title = $(this).attr(\"title\");
    if($(this).attr('checked')) {
    $(\"#search_by ul\").append('<li class='\" + title + \"'></li>');
    } else {
    alert('Inside Else' + title);
    var selector = \"li.\".concat(title); // Just to be sure
    $(selector).remove();
    }
    });
    });
    </script>