1

I'm adding some html to a div using the following jQuery method:

$('#pageTabContent').append($('\
                    <div class="tab-pane" id="'+ticketId+'">\
                        And a whole lot more html here..
                    </div>'));

This works fine, but because I've got way too much html in my javascript I want to move that to a separate file. The problem is that I also need to insert the ticketId in the html. Is there a way using Javascript/jQuery to load the html from a separate file, but still insert the ticketId in it?

[EDIT] Please note that the ticketId is different for every time this piece of code is used. I will be used multiple times within one page load, so I cannot load the ticketId in the html using php. I has to be done client side.

All tips are welcome!

2
  • 1
    You could think over a template engine like Handlebars or Mustache. Commented May 14, 2014 at 15:13
  • 1
    Functions accept parameters. Commented May 14, 2014 at 15:14

2 Answers 2

2

For that specific example, it's pretty straightforward:

$.get("/path/to/file.html", function(html) {
    var newStuff = $(html);
    newStuff.find("div.tab-pane:first").attr("id", ticketId);
    newStuff.appendTo("#pageTabContent");
});

You can generalize that a bit, the basic concept is: 1. Load the HTML, 2. Use jQuery to create DOM elements from it, 3. Use jQuery to find the element in question and modify it, 4. Add to the element.

Another approach is to use some form of templating, either a templating plugin or just DIY:

$.get("/path/to/file.html", function(html) {
    html = html.replace("{{ticketId}}", ticketId);
    $("#pageTabContent").append(html);
});

Again, there are plugins and templating systems to do that for you, which would offer various features over doing your own.

Sign up to request clarification or add additional context in comments.

Comments

0

I generally recommend avoiding dynamic html generation in javascript. There are several good template based frameworks out there. One I like to use in KnockoutJS http://knockoutjs.com/

Another benefit of this approach is change tracking between your model and your html elements.

Comments

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.