Populate list dynamically

1.3k views Asked by At

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!

2

There are 2 answers

0
Tomanow On BEST ANSWER

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');
});
0
ymz On

the answer relies in the function itself. here is the implementation of fancyList from the link you send:

        function fancyList(elem) {

        var this_parent = elem.parents(".fancy-list");

        rel = this_parent.attr("rel");
                var regex = /(<([^>]+)>)/ig;

        first_name = this_parent.find(".fancy-list-footer input#fancy-list-first-name").val().replace(/[<\s]/g, "").replace(/[>\s]/g, "");
        last_name = this_parent.find(".fancy-list-footer input#fancy-list-last-name").val().replace(/[<\s]/g, "").replace(/[>\s]/g, "");

        // more lines of code...

but it can easly change to this:

        function fancyList(elem, first_name, last_name ) {

        var this_parent = elem.parents(".fancy-list");

        rel = this_parent.attr("rel");
        var regex = /(<([^>]+)>)/ig;

        first_name = first_name .replace(/[<\s]/g, "").replace(/[>\s]/g, "");
        last_name = last_name.replace(/[<\s]/g, "").replace(/[>\s]/g, "");

        // more lines of code...

this way the function will better suit your needs and won't force you to generate elements just to get their textual values