I am looking to use the jQuery Templates plugin for some of the forms I create - data is loaded into JSON from ReST Uri.
The problem I am facing is trying to make a conditional expression to display a label or text field depending on the value of the variable.
I really like jQuery templates, but maybe this is the completely wrong way - it seems to me better than creating an element - what do you think?
Here is what I have:
Template:
<script type="x-jquery-tmpl" id="tmplForm"> <table> <tr> <td><label for="title">Title</label></td> <td><input type="text" name="title" id="title" value="${Title}" /></td> </tr> <tr> <td><label for="description">Description</label></td> <td><textarea name="description" id="description" rows="5" cols="20">"${Description}"</textarea></td> </tr> <tr> <td><label for="optiosn">Options</label></td> <td> <table id="env"> {{each Option}} <tr> <td>${$value.Name}</td> <td> //here is where I would like to be an if on the $value.Type //pseudo //if($value.Type == "Label") { // <label for="value">$($value.Value)</label> //} else { // <input type="text" name="value" id="value" value="${$value.Value}" /> //} //this is my very ugly attempted hack - which doesnt work either //${$item.getOptionsElement($value)} </td> </tr> {{/each}} </table> </td> </tr> </table> </script>
Application of data and templates:
<script type="text/javascript"> var data = [ { Id: 1, Title: "Title1", Description: "Description 1", Options: [ { Type: "Label", Name: "labelName", Value: "LabelValue" }, { Type: "TextField", Name: "txtName", Value: "txtValue" } ] } ]; $("#divRForm").empty(); //$("#tmplForm").tmpl(data).appendTo("#divRForm"); $("#tmplForm").tmpl(data, { getOptionsElement: function (option) { if (option.Type == "Label") { return "<label for='value'>option.Value</label>"; } else { return "<input type='text' name='value' id='value' value='option.Value' />"; } } }).appendTo("#divRForm"); </script>
I have one div on the page:
<div id="divRForm"></div>
Thanks for your time, and I hope you can put me on the right track.
Jim
source share