5

I have the method below that queries my server via ajax, JSON data is returned, and I loop through the data and write out to html.

The code works, but it is messy and inefficient. Is there a way to put the html in a template of sorts, instead of writing it out in my javascript code?

Thanks

 $("[name=btnSearch]").on("click", function () {   
   $.getJSON(ajaxMethod + searchTerm, function (data) {
        var html = "";
        var sel = "";
        var name = "";
        var type = "";
        //alert(id);
        var css = "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only";
        $.each(data, function (key, val) {
                sel = val.ID;
                name = val.DisplayName;
                type = "user";
            html += '<tr data-type = "' + type + '" data-result-title = "' + name + '" data-result-id="' + sel + '">';
            html += '<td id="' + sel + '">' + name + '</td>';
            html += '<td><input type="button" class="select" value="select" style="' + css + '"></td>';
            html += '</tr>';
        });
        //html += '<tr><td style="padding-top: 4px;">&nbsp;</td><td style="padding-top: 4px;"><input id="btnAddMembers" type="button" value="Add Members" /></td></tr>';
        $(html).appendTo('[name=' + div + ']');
    });
 });
Anil
  • 21,730
  • 9
  • 73
  • 100
SkyeBoniwell
  • 6,345
  • 12
  • 81
  • 185
  • 1
    You could take a look at jGrid, http://www.trirand.com/blog/?page_id=5 seems to be a nice package for wiring up json data to a table. – Bearcat9425 Jul 26 '13 at 14:45
  • 1
    I think if you want to populate data in script then it would not possible to add it in sperate html template. I would suggest you that make a sperate javascript funtion to build html – usman allam Jul 26 '13 at 14:47

4 Answers4

5

This question does basically what you're looking for (without a plugin, but by adding an additional method to the prototype object).

Read the accepted answer here: Recommended jQuery templates for 2012?

A basic JSFiddle is here: CLICK

Very simple, and easy to edit and extend, the JSfiddle should give you a good idea of how it works.


The Code:

HTML:

<script type="text/template" id="cardTemplate">
<div>
    <a href="{0}">{1}</a>
</div>
</script>

<div id="container"></div>

JS:

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) { 
    return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
  });
};

var cardTemplate = $("#cardTemplate").html();
var template = cardTemplate.format("http://example.com", "Link Title");
$("#container").append(template);
Community
  • 1
  • 1
Anil
  • 21,730
  • 9
  • 73
  • 100
1

You can use one of jquery/js template engines jquery template, jsRender, dust.js. There are a a lot of them.

Bojangles
  • 99,427
  • 50
  • 170
  • 208
YD1m
  • 5,845
  • 2
  • 19
  • 23
1

you can use xml data islands to store html fragments (which would be your templates) in your embedding file. this need not be valid xml if you don't mind writing out the special chars <, >, & in an xml compatible way ( ie. &lt;',>', &#x26; ). the fragments can be turned into dom fragments by calling jQuery.parseHTML(nd_xml.text()), where nd contains the DOM node of the xml node in the data island containing the html fragment. textual substitutions in the template data can be applied in the obvious way.

collapsar
  • 17,010
  • 4
  • 35
  • 61
1

Why don't you use some knockout?

Here's a jsFiddle with an example.

HTML

<input id="searchBtn" type="button" value="Search" data-bind="click: SearchItems" />
<table data-bind="foreach: Items">
    <tr data-type="user" data-bind="attr: { 'data-result-title':DisplayName(), 'data-result-id':Id() }">
        <td data-bind="text: DisplayName()"></td>
        <td>
            <input type="button" class="select" value="select" style="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />
        </td>
    </tr>
</table>

Javascript

var id = 0;

function Item(id, name) {
    var self = this;
    self.Id = ko.observable(id);
    self.DisplayName = ko.observable(name);
}

function ItemsModel() {
    var self = this;
    self.Items = ko.observableArray([]);
    self.SearchItems = function () {
        self.Items.push(new Item(id++, 'Some Name ' + id));
    }
}

$(function () {
    ko.applyBindings(new ItemsModel());
});
sergioadh
  • 1,461
  • 1
  • 16
  • 24