Solved

Dynamically add another HTML Form on Page

Posted on 2013-10-24
18
329 Views
Last Modified: 2013-11-08
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
Comment
Question by:N R
  • 9
  • 6
  • 3
18 Comments
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39599269
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
 
LVL 11

Author Comment

by:N R
ID: 39599373
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
 
LVL 9

Expert Comment

by:Sar1973
ID: 39600006
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
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39600074
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
 
LVL 11

Author Comment

by:N R
ID: 39600976
@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
 
LVL 11

Author Comment

by:N R
ID: 39601000
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
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39601286
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
 
LVL 11

Author Comment

by:N R
ID: 39605954
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
 
LVL 9

Expert Comment

by:Sar1973
ID: 39606146
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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 11

Author Comment

by:N R
ID: 39606152
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
 
LVL 9

Expert Comment

by:Sar1973
ID: 39606171
I can only provide a solution in JS, not jQuery, sorry.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39606253
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
 
LVL 11

Author Comment

by:N R
ID: 39606276
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
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39606690
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
 
LVL 11

Author Comment

by:N R
ID: 39606708
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
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
ID: 39606954
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
 
LVL 11

Author Comment

by:N R
ID: 39630442
Nevermind :)
0
 
LVL 11

Author Comment

by:N R
ID: 39633789
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now