Frexuz
Frexuz

Reputation: 4933

Changing a jQuery-template's HTML before appending to DOM

I have a problem using a jQuery-template the same way as a normal jQuery DOM-object. I need to change the HTML created by the template function, before appending it to the DOM.
The comments in my example below explains what I want to do, and what's wrong.

 <script id="movieTemplate" type="text/x-jquery-tmpl">
  <tr class="week_${week}">
   <td colspan="6">Vecka: ${week}</td>
  </tr>
  <tr class="detail">
   <td>Kund: ${customer}</td>
   <td>Projekt: ${project}</td>
   <td>Tidstyp: ${time_type}</td>
   <td>Datum: ${date}</td>
   <td>Tid: ${quantity}</td>
   <td>Beskrivning: ${description}</td>
  </tr>
 </script>


 <script type="text/javascript">
  var movies = [
    { customer: "SEMC", project: "Product catalogue", time_type: "Programmering", date: "2010-11-08", quantity: 2, description: "buggar", week: 45 },
    { customer: "SEMC", project: "Product catalogue", time_type: "Programmering", date: "2010-11-09", quantity: 3, description: "buggar igen", week: 45 }
  ];
  $("#movieTemplate").tmpl(movies).appendTo("#movieList");

  $("#btnAdd").click(function () {
   //hash with data
   var data = { customer: $("#clients").val(), project: $("#projects").val(), time_type: $("#timeTypes").val(), date: $("#date").val(), quantity: $("#quantity").val(), description: $("#description").val(), week: $("#week").val() }

   //do the templating
   var html = $("#movieTemplate").tmpl(data).find(".week_" + data.week).remove().appendTo("#movieList");
            console.log(html.html()); //Returns null. WHY?!

            var html = $("#movieTemplate").tmpl(data).appendTo("#movieList");
   console.log(html.html()); //Returns the first <tr> only. But appends the full html correctly
   return false;
  });
 </script>

Upvotes: 3

Views: 2030

Answers (1)

Nick Craver
Nick Craver

Reputation: 630379

You're appending the element you removed, if you want to remove the element then append what's left you need to use .end() to hop back in the chain, like this:

var html = $("#movieTemplate").tmpl(data).filter(".week_" + data.week).remove()
                                         .end().appendTo("#movieList");

Currently you're calling .html() on that removed row, since both rows are at the root level of your object and .html() returns the contents of the first matched element.

A better alternative overall though would be to mess with it after it's safely in the DOM, like this:

var html = $("#movieTemplate").tmpl(data).appendTo("#movieList")
                              .filter(".week_" + data.week).remove();

You can test it out here.

Upvotes: 2

Related Questions