Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 339
  • Last Modified:

Dynamically add another HTML Form on Page

I'm trying to find a way to dynamically add another form to my page.

Here is my current form.  I want to have a button that I can click that will add another one of these forms to the page so the user can input another question.

<script>
    $(document).ready(function() {
        $('#questiontype').change(function(){
            var location = $(this).val(),
                div = $('#' + location);

            $('div').hide();
            div.show();

        });
    });
</script>
Question<br>
<select id="questiontype" name="questiontype">
    <option value="">Question Type</option>
    <option value="1">Free Response</option>
    <option value="2">Multiple Choice</option>
    <option value="3">Yes/No</option>
</select>
<br>
<div id="1" style="display:none">
    <form action="submit.php" method="post">
        <input type="text" name="question" placeholder="Question" required /><br>
        <select name="mediatype">
            <option value="">Select Media Type</option>
            <option value="1">None</option>
            <option value="2">Image</option>
            <option value="3">Video Link</option>
            <option value="4">Video Embed</option>
        </select>
        <input type="text" name="media" placeholder="Link">
        <input type="hidden" name="surveyid" value="<?php echo $surveyid;?>"/>
        <input type="hidden" name="submittype" value="3"/><br>
        <input type="hidden" name="questiontype" value="1"/><br>
        <input type="submit" value="Save Question"/>
    </form>
</div>

<div id="2" style="display:none">
    <form action="submit.php" method="post">
        <input type="text" name="question" placeholder="Question" required /><br>
        <select name="mediatype">
            <option value="">Select Media Type</option>
            <option value="1">None</option>
            <option value="2">Image</option>
            <option value="3">Video Link</option>
            <option value="4">Video Embed</option>
        </select>
        <input type="text" name="media" placeholder="Link"><br>
        <input type="text" name="answer1" placeholder="Answer 1" required /><br>
        <input type="text" name="answer2" placeholder="Answer 2" required /><br>
        <input type="text" name="answer3" placeholder="Answer 3" required /><br>
        <input type="text" name="answer4" placeholder="Answer 4" required /><br>
        <input type="text" name="answer5" placeholder="Answer 5" required /><br>
        <input type="hidden" name="surveyid" value="<?php echo $surveyid;?>"/>
        <input type="hidden" name="submittype" value="3"/>
        <input type="hidden" name="questiontype" value="2"/><br>
        <input type="submit" value="Save Question"/>
    </form>
</div>

<div id="3" style="display:none">
    <form action="submit.php" method="post">
        <input type="text" name="question" placeholder="Question" required /><br>
        <select name="mediatype">
            <option value="">Select Media Type</option>
            <option value="1">None</option>
            <option value="2">Image</option>
            <option value="3">Video Link</option>
            <option value="4">Video Embed</option>
        </select>
        <input type="text" name="media" placeholder="Link">
        <input type="hidden" name="answer1" value="Yes" />
        <input type="hidden" name="answer2" value="No" />
        <input type="hidden" name="surveyid" value="<?php echo $surveyid;?>"/>
        <input type="hidden" name="submittype" value="3"/><br>
        <input type="hidden" name="questiontype" value="3"/><br>
        <input type="submit" value="Save Question"/>
    </form>
</div>

Open in new window

0
Nathan Riley
Asked:
Nathan Riley
  • 9
  • 6
  • 3
1 Solution
 
Chris StanyonCommented:
You haven't really specified which bits you want to duplicate, but you have a clone() function in jQuery - something like this:

$('#someButton').click(function() {
   //clone the form with an ID of yourFormId    
   var newForm = $('#yourFormId').clone();

   //give the new form a new ID (IDs have to be unique)
   newForm.attr('id', 'newId');

   //add the new form to the end of the document
   newForm.appendTo('body');
})

Open in new window

0
 
Nathan RileyFounder/CTOAuthor Commented:
I want to clone everything from line 13 on.  I guess I would need to put it in a div to clone it with jquery?

I will give this a shot in the morning and see how it works.
0
 
Sar1973Commented:
In Javascript, you could pick the HTML woth the outerHTML property and insert/add a form HTML with the innerHTML property (see http://www.w3schools.com/jsref/prop_html_innerhtml.asp).
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Chris StanyonCommented:
In your code above, the questiontype select is outside of the form - is this intentional (it will never get submitted).

It would make it easier to wrap everything you want to clone in a DIV - you can then select the whole block. You will need to address duplicate IDs when you clone, so you might want to use classes instead. You'll need to change your change() function to cater for this

FYI - IDs shouldn't start with a number, so technically, this is invalid:

<div id="1" style="display:none">

Open in new window

0
 
Nathan RileyFounder/CTOAuthor Commented:
@ChrisStanyon:
Yes the select outside of the form is intentional.  It's a dropdown that based on selection shows 1 of the 3 divs.

How would I handle the duplicate IDs when I clone then?

EDIT: I'm working on an example on jfiddle and will post link once complete.
0
 
Nathan RileyFounder/CTOAuthor Commented:
http://jsfiddle.net/fMW6Q/2/

So in the above link is how it currently works without issues.  What I want to do is clone the entire thing, I tried wrapping it in a div, but broke my jquery.

I want to be able to click the add question button and it clone it so the user can then enter another question ect....
0
 
Chris StanyonCommented:
Right. It's easier to create a new fiddle to show you the code. You can have a play here:

http://jsfiddle.net/ChrisStanyon/dv86D/I've removed all the form elements just to make the functionality clearer, and added some 'wrapper' elements. I've also used classes to make element selection easier. The code is commented so have a play with it and come back if you need help understanding what I've done.
0
 
Nathan RileyFounder/CTOAuthor Commented:
Ok thanks, all seems to be working well.  The only other issue I see is that the names are not unique on the divs.

Such as "questiontype".  How can I auto increment everytime I add a new question?

Example:
"questiontype"
"questiontype1"
"questiontype2"

ect...
0
 
Sar1973Commented:
You could use an array, with the push method:
var myArray = new array(); (to be declared only once)
var myLength=myArray.length; (will tell you how many elements are in the array)
myArray .push("questiontype"+myLength)
You can also use an iteration if you want to declare and define all the questiontype variables in one time only.
0
 
Nathan RileyFounder/CTOAuthor Commented:
Yeah I wanted to use an array, but since it's cloning I'm not sure how the auto increment will work.

http://jsfiddle.net/ChrisStanyon/dv86D/
0
 
Sar1973Commented:
I can only provide a solution in JS, not jQuery, sorry.
0
 
Chris StanyonCommented:
Hey Gallitin. The 'questiontype' drop down is never part of the form, so it's never submitted (under normal operation). It doesn't need to be unique. Actually, it doesn't even need a name. The jQuery is binding to the 'questiontype' class, and operating on the context of the 'questionWrapper' div.

The only reason you'd need to worry about the input names is if you were submitting everything in one form. Each question is wrapped in it's own form, so that's not an issue.
0
 
Nathan RileyFounder/CTOAuthor Commented:
Ah just realized that in the code.  I think they all need to be within 1 form as I when I hit submit they all need to go into the database. That said I think the questions and answers would then need to have unique names.
0
 
Chris StanyonCommented:
Right. You're going to need to re-think your logic a little more.

Each question has 3 types (Free Response, Multiple Choice and Yes/No). When you change the type from the dropdown, it simply hides the other divs, but all three question types still exist in the form. So for example, if you have 4 questions, you will actually have 12 questions (4 questions * 3 types) that will be submitted in your form. I'm guessing this isn't the behaviour your want.

I think the right approach here may be to have the 'master' question and the 3 different types hidden outside of the form. When you add a new question, it simply clones 'Type 1'. When you change the dropdown, instead of hiding 2 and showing 1, it simply overwrites the question type. This way, each question will only contain one set of question/answers instead of the 3.

In the master question set you would give each element a 'dummy' name that you can then change when you clone.

Give some thought to it, and I'll post some code up in a while that'll do just that.
0
 
Nathan RileyFounder/CTOAuthor Commented:
Ah, I see what you mean, no I wouldn't want it to post 12 questions in the example you gave above.  Yes, I would need the dummy name on each that changes with each clone maybe just a auto increment of a number on the end.  That logic makes more sense, thanks for taking time to help with it, I was having a tough time working it out as it was a couple levels deep.  Will look for forward to the code.
0
 
Chris StanyonCommented:
Right. I've added some code now. You can have a play here:

http://jsfiddle.net/ChrisStanyon/yHDMN/

The inputs in your form are named using arrays question[qNum][fieldName], so when you POST your form to your action script you can easily loop through them. A simple PHP script for showing the data would look something like this:

<?php
foreach ($_POST['question'] as $qNum => $qInfo):
	printf('<p>Question Number: %s', $qNum);
	var_dump($qInfo);
endforeach;
?>

Open in new window

I've commented the code so hopefully it should all make sense.
0
 
Nathan RileyFounder/CTOAuthor Commented:
Nevermind :)
0
 
Nathan RileyFounder/CTOAuthor Commented:
Had another question with file upload in there, figured I would link it as it's you're code.

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28289198.html
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 9
  • 6
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now