Dynamically adding elements to a form and inserting with submit

Using jQuery to add fields.. want to know if I can incorporate PHP

Page 1 of 1

4 Replies - 9077 Views - Last Post: 13 April 2010 - 10:34 AM Rate Topic: -----

#1 Jstall   User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Dynamically adding elements to a form and inserting with submit

Posted 13 April 2010 - 06:19 AM

Hello all,

I am currently working on a site as part of a student work term(already made a couple posts and you guys have been extremely helpful). One of the features of this site is the ability to upload a resume. The resume can have a arbitrary number of "work experiences". I have set up a form and want the user to be able to add new input elements with a click of a button.

Here is a very pared down(for simplicity) version of the form:
<form action = 'resume.php' method = 'post' id = 'resume_form'>
	
<div id = 'work'>
</div>
		
<input type = "button" id = "button"  value = "Add field" / >
</form>




I am using jQuery to add new work experience fields to the form with the click of a button. Here is a pared down version of the jQuery function:
$(document).ready(function() {
	$("#button").click(function(){
		//Html to create a new field
		var newField = "<div class = 'work_experiance'>\
			<p> \
				<label for = 'employer'>Employer: </label><input type = 'text' class = 'employer' name = 'employer' />\
			</p>\
			<p> \
				<label for = 'job_title'>Job Title: </label><input type = 'text' class = 'job_title' name = 'job_title' />\
			</p>\
		</div>";
	$("#work").append(newField);
			
	});
});




I just started learning jQuery yesterday so only know how to do the basic stuff with it so far. My thought was to loop through each work_experience div and do a separate insert into a table called work_experiences. I am thinking that the individual input elements can be accessed through their class or name, so look for a child of the current div with a specific name/class and take the value of that. Could anyone tell me if this is possible? And if so how I could go about doing this? As I said I am still very new to this so I could be going about this all wrong. Any advice or point in the right direction would be very much appreciated, thanks much!

Is This A Good Question/Topic? 0
  • +

Replies To: Dynamically adding elements to a form and inserting with submit

#2 jrm402   User is offline

  • D.I.C Regular
  • member icon

Reputation: 52
  • View blog
  • Posts: 333
  • Joined: 18-March 10

Re: Dynamically adding elements to a form and inserting with submit

Posted 13 April 2010 - 09:42 AM

You probably will want to create each element as an array:
var newField = "<div class = 'work_experiance'>\
                        <p> \
                                <label for = 'employer'>Employer: </label><input type = 'text' class = 'employer' name = 'employer[]' />\
                        </p>\
                        <p> \
                                <label for = 'job_title'>Job Title: </label><input type = 'text' class = 'job_title' name = 'job_title[]' />\
                        </p>\
                </div>";



Notice the brackets I added to the names of the textfields. You can then get the results of the array employer[] and job_title[] on submit. If you need more information on textfield arrays try this: http://www.google.co...ascript&spell=1 (Edit the programming language to the one you wish to use) :)
Was This Post Helpful? 1
  • +
  • -

#3 KuroTsuto   User is offline

  • D.I.C Head
  • member icon

Reputation: 42
  • View blog
  • Posts: 182
  • Joined: 13-February 09

Re: Dynamically adding elements to a form and inserting with submit

Posted 13 April 2010 - 10:10 AM

Hey man!

I'm not quite sure I understood your intentions 100%, but I think I have a pretty good idea, so let me take a whack at it ;). There are two ways in which you might be submitting this form, the way I see it. The first would be using a jQuery function fired when the user hits "Submit" to compile all of their entries into some sort of data object then send it to the server to be interpreted and inserted into the database. The second method would be utilizing your form action and sending the POST data to the server to be inserted - this being the standard approach. Let's break them down:

1) The jQuery way...
an AJAX approach
The first way is nice as it allows you to use the :eq selection modifier to do exactly what you spoke of and loop through your divs. Adding :eq(index) basically allows you to select the "index"th occurrence of the selector detailed before it, so
for(i = 0; i < work_experience_count; i++)
{
    $(".work_experience:eq("+i+")").remove();
}

would effectively loop through all of your work_experience divs and remove them from the DOM.

Alternately, though operating in a similar fashion, there exists jQuery's .each(function(){}) method, which allows you to perform the enclosed function on each matched element, thus making
$(".work_experience").each(function(){
    $(this).remove();
});

The equivalent of the code above.

To actually retrieve the values of the fields, you were correct in thinking that you could use hierarchical selectors to select the fields (or, as is in the following case, the .find method to hone-down a current current selection), after which you could use jQuery's .val() method to return their current value. In this manner you could fire off each individual work_experience entry to a PHP script that would insert them into your database using one of jQuery's useful AJAX calls with something like
$(".work_experience").each(function(){
    var data = {'employer' : $(this).find('.employer').val(), 'title' : $(this).find('.title').val()};
    $(this).load("my_script.php",data);
});


which should pass the data to your PHP script as POST data. Whatever your PHP script outputs will then take the place of the form elements contained within the work_experience div, as per the nature of the .load method.

While you can compile all of the form elements into a single post to your PHP script, it becomes considerably more difficult, unless you compile them as a JSON-compatible object and send them using the more ambiguous $.ajax method.

The final AJAX variation that I'll mention is to use the method I describe below for giving each field a unique name, then simply calling $('#resume_form').submit(), or, alternately, serializing the fields of resume_form with $('#resume_form').serialize() and appending the serialization to the end of the script URL on an AJAX call. This is undoubtedly the easiest of the AJAX methods in regards to your scenario.

2) A more direct approach...
Another way in which to go about this would be to dynamically increment the names of the fields as you insert them, allowing them to be serialized into a URL (as data is when send to a script via GET), among other things. So your pared-down jQuery would become something similar to
$(document).ready(function()
{
    var work_exp_count = 0;

    $("#button").click(function()
    {
        var newField = "<div class = 'work_experience'><p>
              <label for = 'employer'>Employer: </label><input type = 'text' class = 'employer' name = 'employer-"+work_exp_count+"' />\
            </p><p>\
              <label for = 'job_title'>Job Title: </label><input type = 'text' class = 'job_title' name = 'job_title-"+work_exp_count+"' />\
            </p></div>";
        $("#work").append(newField);
        work_exp_count++;
     });
});

That done, you'd actually be already prepared to use the basic "Submit" functionality of the HTML form. Server-side, you could use something like
$i = 0;
while(isset($_POST["employer-{$i}"]))
{
    $work[$i]['employer'] = $_POST["employer-{$i}"];
    $work[$i]['job_title'] = $_POST["job_title-{$i}"];
    $i++;
}

To bring all of the results back into an array for insertion into the database.

So I realize that these probably aren't the cleanest or easiest of solutions, but they're how I thought of the problem, and I hope they help ;). If you have any more questions, I'll be around.

Cheerios, and good luck!
~KuroTsuto
Was This Post Helpful? 1
  • +
  • -

#4 Jstall   User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: Dynamically adding elements to a form and inserting with submit

Posted 13 April 2010 - 10:28 AM

View Postjrm402, on 13 April 2010 - 08:42 AM, said:

You probably will want to create each element as an array:
var newField = "<div class = 'work_experiance'>\
                        <p> \
                                <label for = 'employer'>Employer: </label><input type = 'text' class = 'employer' name = 'employer[]' />\
                        </p>\
                        <p> \
                                <label for = 'job_title'>Job Title: </label><input type = 'text' class = 'job_title' name = 'job_title[]' />\
                        </p>\
                </div>";



Notice the brackets I added to the names of the textfields. You can then get the results of the array employer[] and job_title[] on submit. If you need more information on textfield arrays try this: http://www.google.co...ascript&spell=1 (Edit the programming language to the one you wish to use) :)



Ahhhh I had not thought of that! I was starting to think that I would have to use the jQuery .ajax function to do this but now I think I can pull it off(much easier) using the method you suggested. I am gonna give it a shot, thanks much!
Was This Post Helpful? 0
  • +
  • -

#5 Jstall   User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: Dynamically adding elements to a form and inserting with submit

Posted 13 April 2010 - 10:34 AM

View PostKuroTsuto, on 13 April 2010 - 09:10 AM, said:

Hey man!

I'm not quite sure I understood your intentions 100%, but I think I have a pretty good idea, so let me take a whack at it ;). There are two ways in which you might be submitting this form, the way I see it. The first would be using a jQuery function fired when the user hits "Submit" to compile all of their entries into some sort of data object then send it to the server to be interpreted and inserted into the database. The second method would be utilizing your form action and sending the POST data to the server to be inserted - this being the standard approach. Let's break them down:

1) The jQuery way...
an AJAX approach
The first way is nice as it allows you to use the :eq selection modifier to do exactly what you spoke of and loop through your divs. Adding :eq(index) basically allows you to select the "index"th occurrence of the selector detailed before it, so
for(i = 0; i < work_experience_count; i++)
{
    $(".work_experience:eq("+i+")").remove();
}

would effectively loop through all of your work_experience divs and remove them from the DOM.

Alternately, though operating in a similar fashion, there exists jQuery's .each(function(){}) method, which allows you to perform the enclosed function on each matched element, thus making
$(".work_experience").each(function(){
    $(this).remove();
});

The equivalent of the code above.

To actually retrieve the values of the fields, you were correct in thinking that you could use hierarchical selectors to select the fields (or, as is in the following case, the .find method to hone-down a current current selection), after which you could use jQuery's .val() method to return their current value. In this manner you could fire off each individual work_experience entry to a PHP script that would insert them into your database using one of jQuery's useful AJAX calls with something like
$(".work_experience").each(function(){
    var data = {'employer' : $(this).find('.employer').val(), 'title' : $(this).find('.title').val()};
    $(this).load("my_script.php",data);
});


which should pass the data to your PHP script as POST data. Whatever your PHP script outputs will then take the place of the form elements contained within the work_experience div, as per the nature of the .load method.

While you can compile all of the form elements into a single post to your PHP script, it becomes considerably more difficult, unless you compile them as a JSON-compatible object and send them using the more ambiguous $.ajax method.

The final AJAX variation that I'll mention is to use the method I describe below for giving each field a unique name, then simply calling $('#resume_form').submit(), or, alternately, serializing the fields of resume_form with $('#resume_form').serialize() and appending the serialization to the end of the script URL on an AJAX call. This is undoubtedly the easiest of the AJAX methods in regards to your scenario.

2) A more direct approach...
Another way in which to go about this would be to dynamically increment the names of the fields as you insert them, allowing them to be serialized into a URL (as data is when send to a script via GET), among other things. So your pared-down jQuery would become something similar to
$(document).ready(function()
{
    var work_exp_count = 0;

    $("#button").click(function()
    {
        var newField = "<div class = 'work_experience'><p>
              <label for = 'employer'>Employer: </label><input type = 'text' class = 'employer' name = 'employer-"+work_exp_count+"' />\
            </p><p>\
              <label for = 'job_title'>Job Title: </label><input type = 'text' class = 'job_title' name = 'job_title-"+work_exp_count+"' />\
            </p></div>";
        $("#work").append(newField);
        work_exp_count++;
     });
});

That done, you'd actually be already prepared to use the basic "Submit" functionality of the HTML form. Server-side, you could use something like
$i = 0;
while(isset($_POST["employer-{$i}"]))
{
    $work[$i]['employer'] = $_POST["employer-{$i}"];
    $work[$i]['job_title'] = $_POST["job_title-{$i}"];
    $i++;
}

To bring all of the results back into an array for insertion into the database.

So I realize that these probably aren't the cleanest or easiest of solutions, but they're how I thought of the problem, and I hope they help ;). If you have any more questions, I'll be around.

Cheerios, and good luck!
~KuroTsuto



Ahh yes, the first approach was something I had been thinking about trying to implement and had been reading about today. The other ideas are good ones too, very creative :-). Thanks much for the help, I am gonna try and get this thing working before the end of my work day : - ).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1