Loading template with variables from form fields using jQuery & php
I am trying to create a form that generates an html template. I have the template in a hidden div on the page and am using jQuery to create a new window with the template html, but I can't figure out how to load the contents 开发者_如何学Goof the form fields into the template. I know I should probably be using AJAX, but I don't know where to start.
Suppose you have this template:
<div class="template">
<p class="blah"></p>
<p class="foo"></p>
</div>
and this form:
<form>
<input name="blah" class="blah"/>
<input name="foo" class="foo"/>
</form>
so, for this example we will assume a mapping of form elements to template elements via a common class for each corresponding element:
$("form input").each(function() {
$(".template").find("." + $(this).attr("class")).html(this.value);
});
Try it here: http://jsfiddle.net/dx2E6/
One trick I've been using is using the <script type="text/html">
tag. The browser doesn't render the code, so what I do is something like this:
<script type="text/html" id="template">
<div>
<div class="some_field">{name}</div>
<h4>{heading}</h4>
<p>{text}</p>
</div>
</script>
Your form is something like this:
<form>
<input type="text" name="name" />
<input type="text" name="heading" />
<input type="text" name="text" />
</form>
Then your javascript code would be something like:
$(document).ready(function(){
var tpl = $('#template').html();
$('form input').each(function(){
tpl.replace('{'+$(this).attr('name')+'}',$(this).val());
});
$('div.some_destination').html(tpl);
});
Hope it helps. Tell me if you have more questions regarding this method.
精彩评论