Showing posts with label JQuery Templates. Show all posts
Showing posts with label JQuery Templates. Show all posts

Tuesday, July 19, 2011

JQuery templates and tables : use tbody tag

Lets say you have a table, and you want to hide and show a couple of rows with JQuery.  If you're obsessed with div tags, you might try something like this :
<table id="tbData">
<tr><td>Name</td><td>Phone</td></tr>
<div id="phoneList">
</div>
</table>
You set up a template like this :
<script id="phoneTmp" type="text/x-jquery-tmpl">
<tr><td>${firstname},${lastname}</td><td>${address}</td><td>${phone}</td></tr>
</script>
If you do this, your header will show up at the bottom of the table in Firefox, but Internet Explorer will hate you. Or you will hate Internet Explorer. One of those. I get confused. The solution : use tbody tags instead of div tags when you're inserting, showing, or hiding rows in a table with jquery. This forces me to break my longstanding policy of not using any html tags developed after 2000, but it's saved me a lot of headaches.
<table id="tbData">
<tr><td>Name</td><td>Phone</td></tr>
<tbody id="phoneList">
</tbody>

</table>
Click "Result", or the little "play" arrow to see what this code does



Monday, July 11, 2011

JQuery Templates

JQuery templates let you seperate data from display code on the client. I'll explain why this is useful in future posts (if I get around to it). For now, I'll show you how it works.

First, I include the jquery library, and the jquery Template library.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
Next, I embed a JSON string on my page. (This is javascript, so it goes in javascript tags).
var strData = '[{"firstname":"Dave","lastname":"Stillman","phone":"555-1212","address":"555 1212 Road, Nampa, ID"},{"firstname":"Donald","lastname":"Trump","phone":"555-5512","address":"255 Somewhere Lane, New York NY"}]';
I use eval to turn my json string into a javascript object.
var data = eval("(" + strData + ")");
 Next, I create a template script.  I create it the same way I would include inline javascript in a page, but I give it type='text/x-jquery-tmpl' instead of type='javascript'.  I also give it a unique ID, so I can access it later.
<script id="addressTmp" type="text/x-jquery-tmpl">
<b>${firstname},${lastname}</b><br>
${address}<br>
${phone}<br>
</script>
Next, I add a div where I want the data to be displayed
<div ID="addressDiv" />
Finally, I use a jquery template command to display the data
$("#addressTmp").tmpl(data).appendTo("#addressDiv");
Links

Continue reading to view source code and a live demo