Dynamically add HTML fields to a web form using Javascript/JQuery

by Lasantha Samarakoon on Wednesday, May 18, 2011

Imagine a situation where you need to create a web form which allows users to upload images to a web gallery… In this case you need to allow them to upload multiple images simultaneously. As long as you don’t know how many images the user going to upload, the best way to implement it is create a form with one file field and put a button to dynamically append more file fields to the form.

If you are familiar with Javascript/JQuery, it will be an easy task. You can create it as follows. (Please note that I am using the JQuery library, as it simplifies the code rather than using pure Javascript.)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
// this function will be automatically called when the page is ready to display
$(document).ready(function() {
 // bind the button's click event with the function
 $('#add_button').bind('click', function() {
  // get the html content of the place holder and append new file field into it
  var newContent = $('#place_holder').html() + '<input type="file" name="image[]" value="" /><br />';
  // set the new html content to the place holder
  $('#place_holder').html(newContent);
 });
});
</script>
</head>
<body>
<form method="post" action="">
 <input type="button" value="Add new file" id="add_button" /><hr />
    <span id="place_holder">
     <input type="file" name="image[]" value="" /><br />
    </span>
</form>
</body>
</html>

As you can see, it is a really easy task. But when you put this code into action, you’ll notice there is a small problem with it. The problem is, whenever you add new file field, the files you already selected will lose. To solve it you have to do a little tweak to this code. The tweaked code is as follows.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = 1;
// this function will be automatically called when the page is ready to display
$(document).ready(function() {
 // bind the button's click event with the function
 $('#add_button').bind('click', function() {
  // generate html for new file field and create new place holder too (with new id)
  var newContent = '<input type="file" name="image[]" value="" /><br /><span id="next_position_' + (counter + 1) + '"></span>';
  // set the new html content to the place holder
  $('#next_position_' + counter).html(newContent);
  // increment the counter by one
  counter++;
 });
});
</script>
</head>
<body>
<form method="post" action="">
 <input type="button" value="Add new file" id="add_button" /><hr />
    <span id="file_set">
     <input type="file" name="image[]" value="" /><br />
        <span id="next_position_1"></span>
    </span>
</form>
</body>
</html>

In this method, we first create a place holder for the field. When the user clicks the button, we add the new file field as well as a new place holder with new ID into the current place holder. As long as this code does not re-write HTML for existing fields, contents of the fields will not affect anymore.

Browse internet from the Windows mobile device emulator?

by Lasantha Samarakoon on Monday, May 2, 2011

Windows mobile device emulator, cannot access internet even though your computer is connected to 24x7 internet connection. That is because, the device emulator works exactly same as a virtual machine. Simply, emulator runs an operating system (guest OS) on the PCs operating system (host OS), the same concept behind the virtualization. The emulator works as the hypervisor, and manages resources between the host and guest Oss, but note that it does not establish any connection between the two operating systems.

Since the emulator is another machine, you cannot access the internet through the emulator directly, without establishing a bridge between them (the guest and the host).

Here are the steps you need to follow. (Please note that I’m considering only Microsoft Windows XP operating system, and this will not work same as on Windows Vista/7.)

1. First you have to download and install Microsoft ActiveSync from the Microsoft download center. It is a small setup of 7.5MB.

2. If you are using Visual studio, go to “Tools” menu and select “Device Emulator Manager”. It’ll open the “Device Emulator Manager” window. If you need to start the emulator as standalone application, go to “Run” and type,

C:\Program Files\Microsoft Device Emulator\1.0\dvcemumanager.exe

Device emulator manager in the Visual studio 2008 menubar

Device emulator manager window

3. Once the window opened, right click on the preferred emulator and select “Connect”. In a while, the device emulator will open, and the emulator entry in the “Device Emulator Manager” will show a green arrow.

Green arrow in the the Device emulator manager

Note the "Connect" and "Craddle" menu items in the context menu

4. Again right click on the same emulator entry, and select “Cradle”. Once you click it, the ActiveSync window will appear on the host OS, and will display as “Connected”.

Connected status in the ActiveSync window

5. Now everything is completed. Open Internet explorer in the mobile device and put a URL. You’ll navigate to the page in the internet.

PHP Image Class

by Lasantha Samarakoon on Saturday, February 19, 2011

Today I am going to give you something that I have created using PHP. It is a simple PHP class that can be used to manipulate images easily in an object oriented way. I created this by using basic functions in PHP GD library.

Download

You can download the ZIP archive containing PHP classes by clicking here.

License

I would like to distribute this using GNU/GPL license, so you can add more functionality into it and enhance my basic product.

Functions

This class allows you to manipulate JPEG, GIF and PNG files. It allows image resizing, cropping, merging, rendering, saving and applying filters.

Documentation

Open image

new Image(path-to-file)

Example:

$img = new Image('/home/user/foo.jpg');

You can specify the relative or absolute path as the parameter. Note that this method may throw FileNotFoundException, whenever the method fails to locate the file on the target location.

Resize image

resize(width, height, [unit = ‘px’, [keep-aspect-ratio = false]])

Example:

$img->resize(800, 600, 'px', true);

Resize method allows you to resize image file. Unit can be either ‘px’ or ‘%’.

Crop image

crop(x, y, width, height)

Example:

$img->crop(100, 50, 600, 500);

Crop method allows cropping the image. It takes 4 parameters x coordinate, y coordinate, width and the height.

Merge images

merge(image-object, [x = 0, [y = 0, [opacity = 100]]])

Example:

$anotherImg = new Image('/home/user/bar.jpg');
$img->merge($anotherImg, 100, 100, 75);

Merge method can be used to merge to image objects. That means this method results merger of 2 images. Again it takes 4 parameters; Image object, x coordinate, y coordinate and opacity value. Opacity ranges from 0 to 100, which 0 means transparent and 100 means full opaque.

Save image

save(destination, [file-type = ‘jpg’])

Example:

$img->save('/home/user/foo_edit.png', 'png');

This class can be used to save the resulting image on a storage device. This requires a parameter ‘file-type’ which takes jpg, gif or png as values.

Render image

render([file-type = ‘jpg’])

Example:

$img->render('gif');

Render method allows rendering resulting image on the browser without saving it on a storage device. This requires a parameter ‘file-type’ which takes jpg, gif or png as values.

Filters

Available filters to apply on images are as follows.

  • negative()
  • grayscale()
  • detectEdges()
  • emboss()
  • gaussianBlur()
  • selectiveBlur()
  • brightness(value)
  • contrast(value)
  • colorize(r, g, b, [alpha = 0])
  • sketchy()
  • smooth(value)
  • sephia()

Create your own 3D (Anaglyph) glasses

by Lasantha Samarakoon on Thursday, August 5, 2010

I’m going to deviate from my usual topics today. Let’s consider a small topic in Multimedia. Did you ever tried to create your own 3D glasses for watching 3D movie? If not, today I’m going to tell those steps. If you are not preferred you can buy one around US$ 1 on eBay. But remember, this is so easy and you can create your own one within 15 minutes.

Anaglyph Glass

Before directly jump to our steps, let’s get an idea about this 3D glasses?

There are some videos and images, which provide stereoscopic 3D effect. Our naked eyes are not capable of capturing this effect 100%. So we need to use special glasses called, 3D glasses or “Anaglyph glasses” to help our brains to understand the effect. These anaglyph images/videos are made up of 2 colored layers, offset with respect to each others, which helps to produce the depth effect.

Sample anaglyph image from Wikipedia (Author: Richard Bartz)

Okay, that’s little bit about the concept. Now it’s working time. Here are the materials we need:

  • Card board
  • Template for the glasses. A sketch is available here and you need to have a print out of it. Or else, you can draw your own one too.
  • Red and Cyan (Blue) cellophane papers.
  • And finally the hardest thing, Glue...

Here are the steps:

  1. Cutout the template on the cardboard using the printed (or drawn) sketch.
  2. Cut the cellophane to fit the holes in the template.
  3. Glue or tape them to the holes in the template.  (And make sure you put Red cellophane for the left eye and the cyan cellophane for the right eye.)
  4. Now it’s finished creating your own 3D glasses. Enjoy 3D movies and images using your new 3D glasses.

Watch sample 3D video at http://www.youtube.com/watch?v=-RKI0mtedZw

CSS Typography: Using "font-face"

by Lasantha Samarakoon on Thursday, March 4, 2010

One of the main issues involved with web designing is using proper fonts for the interface. That is because in most of times matching fonts for the user interface design are not standard web fonts. Therefore all the users must have the font to view the web properly. Otherwise the default fonts will be displayed.

There are some alternatives to overcome this issue. One of them is using images instead of text. So the images are rendered with the original font, and that will solve our problem. But it is also not issue free. These are the main issues with it.

Images consume more bandwidth than text. Hence it consumes time also.

Search engines are less sensitive for images. They can’t read the content of image and therefore Search Engine Optimization (SEO) will be an issue too.

Hence images are not the best option. There is another alternative, i.e. using CSS font-face. Font-face is used to define fonts in a style sheet.

@font-face {
      font-family: Bambino;
      src: local("Bambino"), url("Bambino.ttf") format("opentype");
}

Here, you can specify the source (src) of the font. local means if the font defined is available in the local PC, then use it. url means if it is not, download it from the given location. Let’s see how this can use.

/* 
      file: styles.css 
      "Bambino" is the font I used. "Bambino.ttf" is the relevent font file.
*/

@font-face {
      font-family: Bambino;
      src: local("Bambino"), url("Bambino.ttf") format("opentype");
}

h1 {
      font: bold 28px Bambino;
}

p {
      font: 18px Bambino;
}

<!-- file: font.html -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS Typography</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>

<body>

<h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras bibendum dui id arcu ornare eu lobortis orci bibendum. Mauris rhoncus tincidunt vestibulum. Duis imperdiet neque sed turpis viverra suscipit gravida est varius. Nullam euismod tellus quis velit semper vitae vehicula ligula congue.</p>

</body>
</html>

Dynamic progress bar with PHP GD

by Lasantha Samarakoon on Wednesday, February 24, 2010

Today I’m going to show you something regarding GD library of PHP. The GD library is the main library using for Graphics in PHP. By using functions of this library, it is possible to manipulate images with PHP.

In this post, I will show you how to create a dynamic progress bar with PHP. In here the “dynamic” means you can parse 2 values, (i.e. maximum value and the current value) and the PHP script will calculate and render the progress bar dynamically on the screen. The output will come in the format of PNG image file. Hence it is very easy to use in you HTML file.

That’s all about the explanation. So let’s go for codes…

<?php
// filename: progressbar.php
// author  : lasantha samarakoon

// set the type of data (Content-Type) to PNG image
header("Content-Type: image/png");

// extract GET global array
extract($_GET);

// set defaults
if(! isset($max)) $max = 100;
if(! isset($val)) $val = 100;

// this method prepare blank true color image with given width and height
$im = imagecreatetruecolor(400, 20);

// set background color (light-blue)
$c_bg = imagecolorallocate($im, 222, 236, 247);
// set foreground color (dark-blue)
$c_fg = imagecolorallocate($im, 27, 120, 179);

// calculate the width of bar indicator
$val_w = round(($val * 397) / $max);

// create a rectangle for background and append to the image
imagefilledrectangle($im, 0, 0, 400, 20, $c_bg);
// create a rectangle for the indicator and appent to the image
imagefilledrectangle($im, 2, 2, $val_w, 17, $c_fg);

// render the image as a PNG
imagepng($im);

// finally destroy image resources
imagedestroy($im);
?>

OK… that is the PHP script. Now it’s time to display it in the browser. First create a HTML file to display the image. In the IMG tag of the HTML file, type the location of your PHP script and specify 2 values, maximum and current as follows.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Progress Bar</title>
</head>

<body>
 
    <img src="progressbar.php?max=100&val=70" />
 
</body>
</html>

That’s all, and you can see the output…

Create Virtual Host in XAMPP...

by Lasantha Samarakoon on Friday, December 25, 2009

XMAPP is one of the main easy to install Apache distribution which containing MySQL, PHP, Mercury Mail Transport System, Filezilla and etc. And this package is available for many operating systems such as Microsoft Windows, Linux, Mac OS X and Solaris. And the good thing is it’s a freeware. So you can download it free of charge from here.

If you want to use XAMPP, you need to host your web pages and files in XAMPP web folder, which is known as “htdocs”. You can access this folder throw your browser by typing http://localhost in the address bar. So instead of that today I am going to show you how to create another directory in your hard drive and host it in XAMPP. Steps are as follows.

Create a folder in your HD which is going to use as the root directory. As an example I will create a directory in the D:\Virtual\myroot\. So “myroot” will be my new root directory.

1. Open XAMPP installed directory.

2. Go to apache -> conf -> extra directory.

3. In the extra directory there is a file called “httpd-vhosts.conf”. Open it in text editor such as NOTEPAD.

<VirtualHost 127.0.0.1:80>
    DocumentRoot "D:/Virtual/myroot/"
    ServerName myroot.example.com
    <Directory D:/Virtual/myroot/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

4. Save and close the file.

5. Now go to the "Windows" folder. Open System32 -> drivers -> etc folder.

6. In the “etc” directory, there is a file called “hosts”. Open it in a text editor.

7. At the end of the file append following text.

127.0.0.1    myroot.example.com

8. Save and close the file. Sometimes your anti-virus program will block saving. In that kind of situation, allow it.

9. Go to “XAMPP Control Panel” and stop and restart the Apache service.

10. Open your preferred browser and type http://myroot.example.com/.

11. You can see the content of you new virtual host.