Playing with Underscore.js

In this tutorial I’m going to introduce to you a JavaScript Library called Underscore.js. It’s a library used to make your life easier as a Javascript developer. It has a bunch of different functions used for grouping, sorting, and mapping objects.

I’m learning underscore.js as I’m writing this so if you don’t understand something just Google it and enlightenment will be yours.

I recommend that you play with underscore.js on the console, it’s the best place to introduce yourself to a JavaScript library since you will immediately see the output of what you’re writing.

 

Difference

This returns the items in an array which exists on the first argument but does not exist on the second argument. Which means that its return value depends upon the order of the arguments.

var ar1 = [1, 2, 3, 4, 5, 6];
var ar2 = [2, 3, 7, 9, 10, 1];

_.difference(ar1, ar2); //returns [7, 9, 10]

This can also work with arrays composed of strings:

var amp1 = {'names' : ['wern', 'paul', 'falk']};
var amp2 = {'names' : ['w', 'fa', 'wern']};

_.difference(amp2.names, amp1.names); //returns ["w", "fa"]

 

Uniq

The uniq method removes all the duplicates in an object. I don’t know how many arguments it could take but I managed to get two in the example below:

var names1 = ['paul', 'joseph', 'mark', 'matthew']; var names2 = ['joshua', 'ahab', 'michael', 'mark', 'paul']; _.uniq(names1, names2); //returns: ["paul", "joseph",

"mark", "matthew"]

 

All

This is one of my favorites. What his does is to check if all the items in an object meets the criteria that you specify. In the example below we are checking if all the items in the array ar1 is a number:

var ar1 = [1, 2, 3, 4, 5, 6]; _.all(ar1, function(value){ return typeof value == 'number'; });

//returns true

However if we try to put a string and a boolean:

var ar1 = [1, 2, 3, 'im a string', 4, 5, true, 6];

_.all(ar1, function(value){ return typeof value == 'number'; });     //returns false

One possible use case for this method is input validations.

 

Map

I’m not particularly where can I use this one but it looks pretty cool. What this does is to map values to the items in the object that you specify.

var ar1 = [1, 2, 3, 'im a string', 4, 5, true, 6];

_.map(ar1, function(val){ return val + " awesome"; })

And so the output depends on what you specified in the function body. The code above appends the word awesome to every item in the object ar1.

 

Select

This works just like the select query in SQL if ever you have worked with databases before. This requires 2 arguments the first one is the object that you want to use as your data source and the second argument is the function which is equivalent to the actual query in SQL. What I did below is to select all the items in the array ar2 that is greater than 1.

var ar2 = [2, 3, 7, 9, 10, 1]; _.select(ar2, function(val){ return val > 1; })

//returns [2, 3, 7, 9, 10]

 

SortBy

This allows you to sort the items in your object any way you want. In the example below I sorted the array ar2 randomly.

var ar2 = [2, 3, 7, 9, 10, 1]; _.sortBy(ar2, function(val){ return Math.random(val); });

//returns items in ar2 in a random order

 

Rest

Returns all items in the object except the first one.

var x = [1,2,3,4];

_.rest(x); //returns [2, 3, 4] 

 

Initial

Returns all items in the  object except the last one.

var x = [1,2,3,4];

_.initial(x); //returns [1, 2, 3]

 

Find

Returns the first item in the object that matches the criteria that you specified.

var x = [1,2,3,4];

_.find(x, function(v){ return v > 3; }); //returns 4

 

Filter

Similar to select, I don’t really know the difference.

var x = [1,2,3,4];

_.filter(x, function(v){ return v > 2;}); //returns [3, 4]

 

Pluck

Plucks out the values associated with the key that you specify.

var anime = [{title: 'death note', main_char: 'light yagami'},   {title: 'pokemon', main_char : 'ash'}, {title: 'd-grayman' , main_char : 'allen walker'}]; _.pluck(anime, 'main_char');

//returns [light yagami, ash, allen walker]

 

Shuffle

Returns the items in an object in a random order.

var x = [1, 2, 3, 4];
_.shuffle(x);

 

Union

As the name suggests, this merges all the items in the objects that you specify as the argument. Duplicates are removed in the process which means that only unique items are returned by the method.

var x = [1, 2, 3, 4];
var y = [4, 88 , 9, 20];
var z = [5, 5, 7, 22, 1, 2];

_.union(x, y, z);  //returns [1, 2, 3, 4, 88, 9, 20, 5, 7, 22]

 

Intersection

Returns all the items which exists on all of the objects that you specify.

var x = [1, 2, 3, 4];
var y = [4, 88, 2, 1, 9, 20];
var z = [5, 5, 7, 22, 1, 2];

_.intersection(x, y, z); //returns [1, 2]

 

Range

Returns an array of numbers that are within the range that you specify. The usage of the arguments depends on the number of arguments that you specify. If you only specify a single argument it is assumed that the initial value will be 0 and the step will be 1. Remember that the array that is returned is always zero-indexed.

_.range(4); //returns [0, 1, 2, 3]

If you specified 2 arguments then it is assumed that the step is 1 and the first argument is the initial value and the second argument is the terminal value.

_.range(2, 10); //returns [2, 3, 4, 5, 6, 7, 8, 9]

If you specified 3 arguments the first argument is the initial value, the second argument is the terminal value, and the third argument is the step. You can make use of this to easily create a multiplication table of any number.

_.range(2, 20, 2); //returns [2, 4, 6, 8, 10, 12, 14, 16, 18]

 

bindAll

Binds functions into specific events in an object(elements). It’s like event-delegation in jQuery.

Since were doing things in the console and in an empty page, we first need to create the elements that we will be working on.

var spark = document.createElement('input'); //creates an input element
spark.setAttribute('type', 'button'); //set type to button
spark.setAttribute('value', 'spark'); //set value to spark
spark.setAttribute('id', 'spark'); //set id to spark

var body = document.getElementsByTagName('body')[0]; //select the html body tag
body.appendChild(spark); //inject the button into the dom

After creating the element and injecting it into the DOM we set the properties.

var spark_props = {
   name : 'spark boom',
   onClick : function(){ alert('name is:  ' + this.name); }
}

Remember that you can add any property any time you want.

spark_props.boom = 'kapow'

Or even modify existing ones.

spark_props.name = 'bam!!!'

Call the bindAll() method to bind all the properties together.

_.bindAll(spark_props);

Finally, bind the click event to the button using the onEvent method as its action.

$('#spark').bind('click', spark_props.onClick)

 

Once

Creates a clone of the function which can only be called once. One use case that I could think of is when submitting forms sometimes users tend to click on the Submit button multiple times.

var save = _.once(function_to_send_data_to_server);

 

Each

Pretty much like the .each() method in jQuery if you’ve ever used jQuery before. It is used to iterate through the items of the object that you specify.

_.each(['re','mi','fa'], function(va){
   console.log(va);
});
//outputs:
re
mi
fa

 

Functions

Returns an array of functions stored in the object that you specified. The example below returns all the functions associated with Backbone.js, the number of functions returned only shows how lightweight it is.

_.functions(Backbone); returns

["Collection", "History", "Model", "Router",

"View", "noConflict", "setDomLibrary", "sync", "wrapError"]

 

Times

Takes up two arguments the first one is the number of times you want to execute the given function which is the second argument. You can pretty much use this like the _.each method.

var anime = [{title: 'death note', main_char: 'light yagami'},  

{title: 'pokemon', main_char : 'ash'},

{title: 'd-grayman' , main_char : 'allen walker'}];

 

_.times(anime.length,

function(index){console.log(anime[index]['main_char']);})

 

//outputs:

light yagami

ash

allen walker

 

Result

Reminds me of the getters and setters _.result is pretty much like the getter method in every programming language but this time you can either get the value for a particular key or execute a particular function.

 

Conclusion

That’s it! You’ve learned how to use some of the useful methods in underscore.js that you can use in your projects. If you’re already using jQuery you can use underscore.js as an enhancement since they will work together just fine.

 

Resources

How to find unique items in a javascript array

In this quick tutorial I’m going to show you how you can find the unique items in a javascript array. To demonstrate what do I mean when I say unique here’s an example:

I have an array called items which contains a set of letters, some are repeated and some are not.

var items = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'f', 'g', 'a'];

And when I try to get the unique items I should get this:

["b", "c", "e", "f", "g"];

The fact that you’re still reading this means that this is the one that you’re looking for. There’s a lot of ways to do this but here’s the first solution that I came up with:

First, declare an array which will hold the unique items:

var nopairs = [];

Then a variable which will temporarily hold the item which has a pair. This is the current non-unique item in the array.

var haspair = ' ';

And then declare the variable which will hold the current count of the unique items. Initialize its value to zero.

var nopair_ctr = 0;

Next, sort the array using the .sort() method in javascript and then assign it to a variable called arranged.

var arranged = items.sort();

Next, use the jquery.each() method to loop through the sorted array:

$(arranged).each(function(index){
  
});

Inside the loop we checked if the current item is not equal to the next item. Since the array has already been sorted we are assured that the items with the same value are always beside each other. This means that if we do it like this, it will always return false if the current item is equal to the next item.
We also checked if current item is not equal to the current item in the haspair variable. The haspair variable contains the last non-unique item in the array.
If the condition is met, we then store the current item inside the nopairs array using the nopair_ctr as its index. Finally we increment the nopair_ctr by 1 so that we won’t be storing the unique items on the same index.

if(arranged[index] != arranged[index + 1] && arranged[index] != haspair){
	nopairs[nopair_ctr] = arranged[index];
	nopair_ctr++;
}

If the condition above is not met, then we just change the value of the haspair variable to the current item in the array:

else{
	haspair  = arranged[index];			
}	

Finally if you try to output the contents of the nopairs array, you will only see the unique items in the array.

console.log(nopairs);

Life could have been a lot more easier if jquery’s unique() method does it:

console.log(jQuery.unique(items.sort()).sort());

But no, it doesn’t do it since it just pops out the duplicated items in an array and comes up with the following output.

["a", "b", "c", "d", "e", "f", "g"]

 

Conclusion

That’s it for the first article for this new year. You have learned how to use jquery and javascript to sort an array using the .sort() method in javascript, you also learned how to use jQuery’s unique() method to remove duplicates in array, lastly you have learned how to find the unique items in a javascript array.

How to unformat and save formatted numbers using accounting.js

Okay, so this is part 2 of the tutorial that I have written yesterday on the basic usage of accounting.js.

How to convert numbers to currency format using accounting.js

This time I’m going to show you how you can unformat those formatted numbers so that it can be stored in the database. I’m also going to show you how to save the data using ajax.

Since this is the second part of an existing tutorial. The requirements are still the same. You only need to install a database server like Wampserver if you want to have a database where you can save data.

We have a few changes on the markup. If you followed along in the first part its better if you just create a new file.

<p>
<label for="raw_num">Raw Number 1:</label>
     <input type="text" name="raw_num" id="raw_num">
</p>
<p>
     <label for="raw_num">Raw Number 2:</label>
     <input type="text" name="raw_num2" id="raw_num2">
</p>
<p>
     <label for="raw_num">Raw Number 3:</label>
     <input type="text" name="raw_num3" id="raw_num3">
</p>
<p>
     <label for="form_num">Formatted Number 1:</label>
     <input type="text" name="form_num" id="form_num" class="formnum">
</p>
<p>
     <label for="form_num">Formatted Number 2:</label>
     <input type="text" name="form_num2" id="form_num2" class="formnum">
</p>
<p>
     <label for="form_num">Formatted Number 3:</label>
     <input type="text" name="form_num3" id="form_num3" class="formnum">
</p>
<p>
     <input type="button" id="btn_save" value="save">
</p>

Does the markup suggests anything to you? To kill the question, yes were going to make use of arrays here in order to capture all the values in the text fields which has the formnum class. Formnum is short for formatted number.
As the name suggest, the one and only button in the markup is used for saving the data into the database.

Next is the script itself.
First, ensure that the user only gets to input numbers:

$('#raw_num, #raw_num2, #raw_num3').numeric();

Then format the raw numbers. Nothing new here, we just repeated what we did on the first tutorial.

$('#raw_num').keyup(function(){
	var raw_num = $(this).val();
	var form_num = accounting.formatMoney(raw_num);
	$('#form_num').val(form_num);
});
	
$('#raw_num2').keyup(function(){
	var raw_num = $(this).val();
	var form_num = accounting.formatMoney(raw_num);
	$('#form_num2').val(form_num);
	});
	
$('#raw_num3').keyup(function(){
	var raw_num = $(this).val();
	var form_num = accounting.formatMoney(raw_num);
	$('#form_num3').val(form_num);
});

Finally, the action to be performed when the user clicks on the save button. To explain things, on the 2nd line, we just declared an array called raw_num in which the unformatted numbers will be stored. On the 3rd line (Whitespaces isn’t considered a line), we loop through each of the elements which has a class of formnum. Then we used the unformat method of accounting.js to turn the number back to its raw form. Then on the 6th line, we called the jquery’s $.post function. The $.post function is a simpler version of the $.ajax function. Which only requires a minimum of 2 arguments, one is the php file that would talk to the server, and the second is the variable that you’re going to pass on to that php file. In this case we want the array of unformatted numbers to be the variable that’s going to be passed.

$('#btn_save').click(function(){
     var raw_num = [];
	
     $('.formnum').each(function(index){
	raw_num[index] = accounting.unformat($(this).val());
     });
	
     $.post('save.php',{'raw' : raw_num});
});

 

Maybe you’re wondering why do I still bother unformatting the number if there is already an unformatted version of that number. My answer would be yes, there’s really no purpose in formatting the number then unformatting it again if there exist a copy of the unformatted number.
But what if there’s none? What if the formatted version of the number should also be placed wherever the original number is.

And I almost forgot what the heck is save.php. Well save.php will be the one who talks to mysql. Saying: “could you please save this bunch of numbers into your database?“ Here’s what it contains. What we did here was to loop through the contents of $_POST[‘raw’]. ‘Raw’ is the name of the variable that we assigned in the javascript earlier.

<?php
require_once('randomconfig.php');

foreach($_POST['raw'] as $num){
	$db->query("INSERT INTO accounting_js SET numbers='$num'");
}
?>

 

Conclusion
Accounting.js is indeed a very nice tool for number formatting. But there are more features which aren’t discussed here, so you might as well check out the official site for more information regarding accounting.js.
Aside from accounting.js I also showed you how to loop through elements containing data, and save data into the database using jquery’s $.post method.

Remember inputted data using jquery cookies

I know what brings you here.
But before that, here’s what were going to do here:

  • Setting up client-side cookies using jquery
  • Using cookies to automatically fill up a form

 

Requirements

 

I decided to ditch the assumptions and proceed with the procedures right away. I figured that most of you doesn’t actually read it.

 

Procedure

As usual, do the housekeeping. Include those 2 files I mentioned in the requirements.

<script src="jq.js"></script>
<script src="jquery.cookie.js"></script>

Create the form:

<form name="x" action="formcookie.php" method="post">
<p>
Remember input?
<input type="checkbox" name="rem" id="rem">
</p>
<p>
name:
<input type="text" name="name" id="name">
</p>
<p>
course:
<input type="text" name="course" id="course">
</p>
<input type="submit" id="btn_submit" value="save">
</form>

Nothing new here, I’m still bad at indenting the code properly. Please bear with me.
The code above is the form that we are going to use. As you can see it has a checkbox which the user can check in order to save his input into a cookie. And uncheck it to delete any existing cookie. That’s just a scenario of what it does, we didn’t actually wrote the code that does what I just said.

Next, write the usual thing to do when using jquery: Initialize elements on page load:

<script>
$(function(){
  //code goes here
});
</script>

Then we assign values to the name and course fields to be equal to the cookies that were going to declare shortly. You can actually check if those cookies exist before assigning it to the textfields. But I didn’t get any error on Firebug so I think this is just fine.

$('#name').val($.cookie('name'));
$('#course').val($.cookie('course'));

Right after the user has clicked on the submit button we want to execute something:

$('#btn_submit').click(function(){
  //something
});

You’re asking what’s something? Here’s the algorithm:

  1. check the if the checkbox is checked
  2. if checked assign the cookies
  3. if not clear the cookies

Next time the page loads: values are automatically assigned to the text fields if the cookies exists.

Okay, so here’s what goes as inside the btn_submit() function. Assign the values which are currently in the text fields into the variables name and course:

var name = $('#name').val();
var course = $('#course').val();

Also assign the status of the checkbox to a variable. The variable cook will have a value of true if the checkbox is checked and false if its not:

var cook = $('#rem').attr('checked');

That’s it! All that is left to do now is to write the code that will assign the cookie if the checkbox is checked. And the code that will clear the cookie if the checkbox isn’t checked:

if(cook == true){
    $.cookie('name', name);
    $.cookie('course', course);
}else{
    //clear cookies
    $.cookie('name', '');
    $.cookie('course', '');
}

 

Conclusion

You have just learned how to use the jquery cookies plugin to create client-side cookies. You can actually use this to add a remember me functionality on your login form or any other kind of form which needs to be automatically filled up based on user preferences.

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.

Hide or show multiple form elements using jquery and fieldsets

In this tutorial I’m going to show you how you can hide or show multiple form elements in one go. That is by grouping those form elements in an html fieldset.

 

Requirements

  • jquery core

 

Procedure

First, do the housekeeping.

<style>
#full{
    width:500px;
}
</style>
<script src="jq.js">
</script>

I’m really lazy today, so I didn’t include the style and the script type. This works, but its not really a good practice.

Next, create the form elements.

<input type="button" id="hide" value="hide/show"/>

<fieldset id="full">
<legend id="full_legend">Fieldset_hideshow</legend>
<p><input type="text" name="a" placeholder="a"/></p>
<p><input type="text" name="b" placeholder="b"/></p>
<p><input type="radio" name="c"/>
<input type="radio" name="c"/>
<input type="radio" name="c"/></p>
</fieldset>

We grouped the 2 text fields and the 2 radio buttons inside the fieldset. So that we won’t be accessing those elements one by one if we want to hide/show them.

Finally, we create the script which will hide/show the fieldset and all of the elements inside of it.

<script>
$(function(){

$('#hide').click(function(){
    $('#full').toggle('fast');
    });
});
</script>

In case you don’t know toggle is just a shortcut for .show() and .hide() functions. And here’s what it does: first it checks if the element is hidden or not. Might be something like this, if you hand code it:

if($(element).is(":visible")){
    //hide it
}else{
    //stay put
} 


Conclusion

I can’t really think of a good conclusion, because it seems like I’m only repeating what I’m saying every time I make a conclusion. And what’s worst is that what I’m saying doesn’t really fit the description of a conclusion. Don’t you agree? Anyway, again thanks for reading!

How to generate form fields using javascript

In this tutorial I’m going to show you how you can generate form fields using javascript and jquery.
This is useful when you need to conserve space on your form and you only want to show the optional fields if the user needs it.

Requirements


Procedure

Yeah, I  guess I’ll just call this portion ‘procedure’ from now on. You might have notice the inconsistency if you’re a regular reader of my blog.

First, I need you to setup your folder structure. You must know how to link your jquery core file. If its just inside the same folder as the file that we are building right now then it might look something like this:

<script type="text/javascript" src="jq.js">
</script>

 

Means

Second, let’s build the form elements which will serve as a way to create the dynamically generated form fields. For this tutorial, we will be using a button.

<input type="button" id="glink" value="generate link"/>
<input type="button" id="gtext" value="generate textbox"/>
<input type="button" id="gradio" value="generate radio"/>

In the sample code above. I have 3 buttons. One that generates a link, the other generates a text field, and the last one generates a radio button. As you can see from the values.

Parent

Third, let’s build another set of form elements. This will serve as the parent for the form elements which will be generated:

<div id="link_div"></div>
<div id="text_div"></div>
<div id="radio_div"></div>

 

Analogy

In real world (yeah, I guess this is my first time doing an analogy), a child needs a parent in order to be born or exist. They can’t just pop out of nowhere. They need someone to bring them into this world. And so are form elements. In the sample above, there is a separate parent element for links, text fields , and radio buttons. So that they won’t just scatter everywhere in the page once they’re created.

 

Housekeeping

Fourth, let’s go back to jquery and javascript. I’m talking about the code which we are going to put inside the <script></script> tags. If you don’t already have that, then I think its time you type it on your text-editor. Then do the housekeeping:

$(function(){

    var num = 0;
    var num2 = 0;
    var num3 = 0;

});

If you’re a psychic or someone who has mental powers. Then you might now what those 3 variables are for. If not, then here’s my answer since I’m no good at naming things: variables num, num2 , and num3 will be used as an index to keep track of how many links, textboxes, or radio buttons are generated. They will also serve as the id attribute for each element. If this is not clear to you, then you’ll see what I mean once you see the output.

 

Functions

Fifth, let’s now create the functions that will be performed when users click on each of the buttons that we created a while ago. Prepare yourself because here’s a big chunk of code:

$('#glink').click(function(){

    var link = document.createElement('a');
    link.setAttribute('href', 'mypage.htm');
    link.setAttribute('id', 'link' + num);

    document.getElementById('link_div').appendChild(link);
    document.getElementById("link + num).innerHTML = "spanner" + num + "<br/>";
    num++;

});

On the first line, we declared a function which will be called if the user clicks on the button with an id attribute of glink (glink for generating link). Then we declared a variable called link, which will hold the value returned by the create element javascript function. Create element takes up 1 argument, and that is the actual html element that you want to create. In the code above, were trying to create an anchor element (link). If you want to create an image you do it this way:

document.createElement('img');

As you can see, its not just for form elements. You can use the create element function to create any html element which can be seen.

Next, we set the attributes for the newly created form. Since it’s a link, it needs an href attribute which will contain the actual link (like this: http://google.com). And also an id attribute, which will differentiate it from the rest of the links that will be generated. And to make the id as unique as possible, I added the num variable. Which will be incremented every time we generate a new link to the page.

link.setAttribute('href', 'mypage.htm');
link.setAttribute('id', 'link' + num);

Then we append it to its parent element. Which is the div element with the id attribute of link_div:

document.getElementById('link_div').appendChild(link);

Lastly, we try to give it a form. So that we can see that its actually there:

document.getElementById("bolok" + num).innerHTML = "spanner" + num + "<br/>";

And don’t forget the code which makes the unique id thing possible:

num++;

 

Conclusion

I guess one example should do. Just check out the files that I used in this tutorial in the files section of this blog. If you want to see the code for the textbox and radio button generation.