Here, I want to show how to call a javaScript funtion in jQuery template using jQuery tmpl plugin.
For this we need jQuery plugin and jQuery tmpl plugin.
Here, I am checking word 'phone' of json object, if it contains returns true else false. The following is the jquery template.
<script id="myTemplate" type="text/x-jquery-tmpl">
<li>
${firstName} ${lastName},
{{if $item.myMethod() }}
my phone no. is <span>${Contact}</span>
{{else}}
my email is <span>${Contact}</span>
{{/if}}
</li>
</script>
Here the javascript function is myMethod().
The following is the binding of jquery template and json object.
$("#myTemplate").tmpl(jObj,{
myMethod: function() {
debugger;
var text = this.data["ContactType"];
if (text.toLowerCase().indexOf('phone') > 0) {
return true;
}
else
return false;
}
}).appendTo("#myDiv");
Here, I am fetching ContactType in myMethod,but can get any data calling by name. Json data is:
var jObj = [
{ firstName: "Vijay", lastName: "Babu", ContactType:"Mobile Phone",Contact:"123456789" },
{ firstName: "Yashitha", lastName: "Bhagya", ContactType:"Office Phone",Contact:"08856-23456" },
{ firstName: "Nag", lastName: "Bunny", ContactType:"Office Email",Contact:"[email protected]" },
{ firstName: "kusuma", lastName: "vinitha", ContactType:"Personal Email",Contact:"[email protected]" }
];