Generating form elements using jquery

Last time I showed you how you can generate form fields using javascript and a little bit of jquery:

How to generate form fields using javascript

This time, I’ll show you how you can do it in jquery with a little bit of javascript.

Requirements

  • Jquery core

Assumptions

Yep! It’s the first time that I’m going to do this section. A proper introduction is needed. Assumptions section is where I speak of  all the things which you need to know first before trying to read a tutorial. So in this tutorial, I assume that you already know the basics of jquery and javascript. That’s all there is to it, if you already know javascript and jquery, and you have all the requirements. Then you’re ready to start.

Procedure

First, do the housekeeping. I won’t tell you how to do it…
Just kidding! When I say housekeeping, it means including all the files which are needed on your page. And the bit of code which will let you perform actions using jquery.

$(function(){
       //form generation code goes here
});

Second, create the form which will be used by the user to generate another form element.

<form name="x" action="jquery_generatefields.php" method="post">
<input type="button" id="jq_gen_txt" value="generate text field"/><br/>
<input type="button" id="jq_gen_sel" value="generate select field"/>

<div id="gen_txt_fields"></div>
<div id="gen_sel_fields"></div>
<input type="submit"/>

If you have red my last tutorial on creating form elements using javascript. You might already know that the 2 buttons in the form will be the event launcher. And the 2 divs is where the generated field goes to.

You might also notice that I have action and method attributes for the form. That’s because I’m going to make a 2nd part for this tutorial in which we will actually save the inputted data in those dynamically generated fields into the database. Stay tuned for that.

Going back to javascript. Inside the document.ready() function. Create 2 new variables. This will serve as the index for the elements that the user is going to create later on. If you didn’t catch what I mean by that. I said that were going to use it for the id attribute for each dynamically generated form elements.

var num_txt = 0;
var num_sel = 0;

By the names of those variables, you might already predicted that what were going to generate are:

  • Text field
  • Select field

Next, create the function that will execute if the button for generating text fields has been clicked:

$('#jq_gen_txt').click(function(){
  //code for text field generation goes here
}

Inside the function. We create the element input. Then add attributes id, name, and placeholder to it. Id is optional, if you want to have a unique identifier for the form elements that are created then put the id attribute. Name attribute is mandatory for this tutorial. Since were going to use it later to access the value of that specific field for our database. Finally we append it to the div with the id attribute of gen_txt_fields.

var txt = $("<input>").attr({'id': 'tx' + num_txt,
 'name': 'tx[]',
 'placeholder':  num_txt}).appendTo('#gen_txt_fields');

Next we also create a button which can be used by the user to remove the text field that has been created.

var rem_btn = $("<input>").attr({'type' : 'button',
 'id' :  num_txt,
'value' : 'remove'}).appendTo('#gen_txt_fields');

The code is the same, the only difference are the attributes which are being applied. Type attribute is used to determine what type of input field will be generated, this is a mandatory attribute. Since without it, you can’t possibly know what type of input field will be generated because there are lots of input fields. Some of those are:

  • radio buttons
  • checkboxes
  • text fields
  • password fields

And with the advent of html5. Another set of fields has been added to the list:

  • email fields
  • telephone number fields
  • number fields

I think there are still more, but I can’t recall them. And I can’t even Google them since my internet connection has already been turned off at this moment.

Oops, don’t forget to include the code which will increment the variable num_txt everytime the user clicks on the button:

num_txt++;

Next create the function for creating select fields:

$('#jq_gen_sel').click(function(){
   //code for select field generation goes here
}

First, you have to create the select field.

var sel = $("<select>").attr({'id' : 'gender' + num_sel,
'name' : 'gender[]'}).appendTo('#gen_sel_fields');

Next, will be its options:

var male = $("<option>").attr({'id' : 'male' + num_sel ,
 'value' : 'Male'}).text('Male').appendTo(sel);

var female = $("<option>").attr({'id' : 'female' + num_sel,
 'value' : 'female'}).text('Female').appendTo(sel);

We both append those to the select field which is currently assigned to the variable sel. So its safe to make use of the variable name. But you can also make use of the id of the select field, that will also work.
Remember that the value is different from text:

  • value – actual value of the option
  • text – the value which is being shown in the option. (innerHTML as you might call it)

Then finally the incrementing code:

num_sel++;

Next, we write the code for the button which removes/deletes the generated text field (I’ll leave the removal of select field to you).

$('input[id^=rem_btn]').live('click', function(){
   //code for input field removal
}

The code is a bit different from usual. Since we didn’t use the click() event directly. We used the live() event instead. Its always been my practice to use this in cases wherein I need to access a dynamically generated form.

var clicked = $(this).attr('id');
var tx_id = 'tx' + clicked;
$("#" + tx_id).remove();
$(this).remove();

In the code above, we accessed the Id attribute of the button, and stored it in the tx_ad variable together with the prefix that we used in the text fields id which is the word ‘tx’. We then performed a simple remove() function to remove the text field with the same index as that of the button.

Conclusion

That’s it for this tutorial. You’ve learned how to generate form elements using jquery. Next time I’m going to show you how you can save the data inputted in those dynamically generated text fields into the database.

One thought on “Generating form elements using jquery

  1. That is just so cool. It’s a shame the dam freakin variables generated in this way don’t actually go back correctly when the page is posted (as proved with Firebug, they have nothing in them). Or if they do, it’s some way I’ve never seen before. Another good reason to stick with server-side stuff and leave this jquery / javascript crap to designers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s