2

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?

2
  • What is the correct fieldset? You're adding a fieldset element every time you add a paragraph based on your code... Commented Jul 6, 2011 at 12:48
  • I would create a fieldset for each cap and his paragraph. Paragraph will be added on the fieldset cap. Commented Jul 6, 2011 at 12:49

2 Answers 2

2

You could use something like this: http://jsfiddle.net/UX5bz/7/

Which is using .parent() to locate where to append:

$(elem).parent().append(htmlcode);
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.