I have to create a dynamic form. The structure is: Each Cap. can have many Paragraph, and the form can have many Cap.
Here there is an example: http://jsfiddle.net/michelejs/UX5bz/
I would 开发者_运维技巧that if I add a Paragraph it will be added in the correct fieldset. How can I do this?
You could use something like this: http://jsfiddle.net/UX5bz/7/
Which is using .parent()
to locate where to append:
$(elem).parent().append(htmlcode);
Here is a working version of your code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var capitoli = 1;
$('#addCap').live("click", function () {
capitoli = capitoli + 1;
var htmlcode = '<fieldset id="capitolo1">' + '<legend>Cap' + capitoli + '</legend>' + '<input type="text" value=""/>' + '<input type="button" class="addParag" value="Add Paragraph"></fieldset>';
$("#frm").append(htmlcode);
});
$('.addParag').live("click", function () {
var htmlcode = '<fieldset id="parag">' + '<legend>Paragraph</legend>' + '<input type="text" value="name paragraph"/>' + '<input type="button" id="removeParagrafo" value="Remove Paragraph"></fieldset>';
$(this).parents("fieldset").append(htmlcode);
});
});
</script>
</head>
<body>
<form id="frm">
<div>
<input type="submit" name="g" value="Submit" id="g" />
<input type="button" id="addCap" value="Add a Cap">
</div>
<fieldset id="cap1">
<legend>Cap1</legend>
<input type="text" value="name cap1"/>
<input type="button" class="addParag" value="Add a Paragraph">
</fieldset>
</form>
</body>
</html>
精彩评论