0

I want to execute a function that appends (jQuery) a li to an ul. Now I want to pass a string as a parameter that looks like:

v.name + " by " + v.artist

The problem is that the v.name and v.artist don't exist outside the function, because the function contains an .each loop:

function showAllItems (data, displayText) {
    $("ul.result-list").empty();
    $.each(data.results, function (k, v) {
        var name = eval(displayText);
        if ($("ul.chosen-list input#" + v.name).length == 0) {
            $("ul.result-list")
                .append($("<li>")
                    .append($("<input>", {id: v.name, value: v.name, type: "checkbox"}))
                    .append($("<label>", {html: name, for: v.name, class: "clickable"})));
        }
    });
}

What I am using now is eval(displayText) to convert a string into a real variable. But now I can't pass something like I said earlier (v.name + " by " + v.artist).

In short, I want to print a string containing variables that don't exist until the .each loop.

I hope someone can help me!

Thanks in advance,

Ian Wensink

2
  • Why wouldn't it exist, and what do you mean when you claim you're converting a string into a "real variable" ? Commented Mar 26, 2015 at 21:21
  • Well, I want to print v.name, but v doesn't exist outside the each loop, because that's the value. So I want to pass into the function that it needs to print v.name, but v.name doesn't have a value yet. That's why it has to be a string, which needs to be converted into a variable. Commented Mar 26, 2015 at 21:29

1 Answer 1

1

Use a callback function to create the value:

function showAllItems (data, getDisplayText) {
  $("ul.result-list").empty();
  $.each(data.results, function (k, v) {
    if ($("ul.chosen-list input#" + v.name).length == 0) {
      var name = getDisplayText(v);
      $("ul.result-list")
        .append($("<li>")
          .append($("<input>", {id: v.name, value: v.name, type: "checkbox"}))
          .append($("<label>", {html: name, for: v.name, class: "clickable"}))
        );
    }
  });
}

Usage:

showAllItems(data, function(v){ return v.name + " by " + v.artist; });
Sign up to request clarification or add additional context in comments.

9 Comments

The .append functions need to be fixed too... appending the input and label to the ul and not the li
But they should be appended to the li, don't they?
@Mottie: They should be inside the list item. You can't have them in the list outside a list item.
Look at the source of this demo in Chrome... the lis, inputs and labels are all direct children of the ul.
Well, besides that discussion, your callback idea worked! I am so thankful!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.