Search code examples
javascriptjqueryhtmljquery-widgets

Populate list dynamically


Using jQuery FancyList from http://jquerywidgets.com/widgets/fancy-list/

I am trying to insert a <li> through code, not by a user click action.

My issue lies in the this keyword, specifically the following lines:

    $(".fancy-list-footer .add").click( function() {
        $('.tab-container .user-information .first-name:last').val('').removeClass('placeholder');
        $('.tab-container .user-information .last-name:last').val('').removeClass('placeholder');
        fancyList($(this));
    });

I would like to be able to pass a first name and last name without having to populate the textboxes - a for loop will do this.

I tried changing the fancyList(elem) function to fancyList(elem, firstName, lastName) but I couldn't seem to get the correct value for elem - I tried var elem = document.getElementByClassName('fancy-list-footer') because I thought that's what the $(this) referred to in the button click, but this didn't work either.

Codepen: http://codepen.io/anon/pen/vEYaqa?editors=101

Any help appreciated!


Solution

  • You can make a function like so that will add a name:

    function addToFancyList(first_name, last_name) {
        $('.fancy-list').find(".fancy-list-content-list:last").append("<li><div class='person'><span class = 'first'>" + first_name + "</span><span class = 'last'>" + last_name + "</span></div><div class='clear'></div></li>");
    }
    

    And simply call it like so:

    $(function () {
        addToFancyList('Tom', 'Someone');
    });