<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Kevin Dubois &#187; javascript</title>
	<atom:link href="http://kevindubois.com/blog/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://kevindubois.com/blog</link>
	<description>A LAMP consultant in the greater Salt Lake City Area</description>
	<lastBuildDate>Mon, 24 Oct 2011 16:32:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Creating an advertisement widget for external websites using JavaScript</title>
		<link>http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites/</link>
		<comments>http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 17:42:58 +0000</pubDate>
		<dc:creator>Kevin Dubois</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[advertisement]]></category>
		<category><![CDATA[widget]]></category>

		<guid isPermaLink="false">http://kevindubois.com/blog/?p=41</guid>
		<description><![CDATA[Tweet If you work with Google Analytics or Google Adsense, you&#039;ve undoubtedly worked with the little code bits they ask you to include in your website.  This tutorial will teach you how to create your own widget that people can &#8230; <a href="http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="border:1px solid #808080;background-color:#F0F4F9;">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fkevindubois.com%2Fblog%2F2009%2F11%2F16%2Fcreating-advertisement-widgets-for-3rd-party-websites%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" style="border:none; overflow:hidden; width=85px; height:21px;"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites/"  data-text="Creating an advertisement widget for external websites using JavaScript" data-count="horizontal">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites/" data-counter="right"></script></div>			
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites/"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><p>If you work with Google Analytics or Google Adsense, you&#039;ve undoubtedly worked with the little code bits they ask you to include in your website.  This tutorial will teach you how to create your own widget that people can include on their website by pasting a similar piece of javascript.</p>
<p>First off, you&#039;ll need to create a javascript file, accessible from 3rd party systems.  Typically you won&#039;t have to do anything for this &#8211; just make sure you can access the file from any browser and host with the http protocol.</p>
<h2>1) The simple and easy (but limited) solution</h2>
<p>So let&#039;s go ahead and create mywidget1.js, and tell it to output the string &#039;Hello World&#039;.</p>
<blockquote>
<pre>document.write("hello world!");</pre>
</blockquote>
<p>Now, we&#039;ll write the code bit that will be included on the 3rd party sites:</p>
<blockquote>
<pre>&lt;script type="text/javascript"  src="http://www.kevindubois.com/demos/js/mywidget1.js"&gt;&lt;/script&gt;</pre>
</blockquote>
<p>Simple, right?  If that satisfieds your needs, all the better, but most people will want a little more functionality.</p>
<p>Either way, you can see a demo for this one at <a title="widget1" href="http://www.kevindubois.com/demos/widget1.html" target="_blank">http://www.kevindubois.com/demos/widget1.html</a> (the js code is at <a title="widget1 javascript" href="http://www.kevindubois.com/demos/js/mywidget1.js" target="_blank">http://www.kevindubois.com/demos/js/mywidget1.js</a>)</p>
<p>There are ways to pass variables and there are ways to handle secure servers, so if that&#039;s what you&#039;re interested in, please continue to read!</p>
<h2>2) The more advanced (but still pretty easy) solution:</h2>
<p>The files stay the same, only the code within will get a little more chunky.  My sample will be based on the assumption that you&#039;re sending an advertisement widget to the 3rd party sites &#8211; but it really could be anything you want, just change the parameters in whatever you want.</p>
<p>Let&#039;s start with the 3rd party code this time.  We&#039;ll write the javascript tags again,  but this time we&#039;re not going to include the location to the js file in the tag but rather, we&#039;re going to tell the browser to write another javascript codebit from within the first javascript tag.  This is necessary to pass some parameters to the js file; and to write some code around secure sites (or not) issues:</p>
<blockquote>
<pre>&lt;script type="text/javascript"&gt;
 referral_code = "MQI74";
 ad_code = "aa";
 ad_width = "200"; // optional
 var myHost = (("https:" == document.location.protocol)   ? "https://www." : "http://www.");
 document.write(unescape("%3Cscript src='" + myHost +    "kevindubois.com/demos/js/mywidget2.js' type='text/javascript'%3E%3C/script%3E"));
&lt;/script&gt;</pre>
</blockquote>
<p>referral_code, ad_code and ad_width are parameters that are being sent to the js file.  myHost detects whether we&#039;re on a secure site or not, and will change the path to reflect that.  Note that this will only work if you have a secure certificate on your end too.  The reason why I included this, is because some browsers will return a warning on the 3rd party secure site if your js file is not secure, saying that some items on the site are not secure.  The html tags are being escaped ( &lt; = %3C and &gt; = %3E ) and then unescaped, because otherwise the browser will interpret these tags incorrectly.</p>
<p>Let&#039;s go back to the js file and add some more code to handle the parameters and the security:</p>
<p>Start the js file by figuring out the security again:</p>
<blockquote>
<pre>var myHost = (("https:" == document.location.protocol) ?   "https://www." : "http://www.");</pre>
</blockquote>
<p>The parameters you passed are directly available, so you can start using them immediately. In my case, I added a switch statement to show different ads (sort of like google adsense, where you can show different ad sizes and types by changing the ad code).  Make sure you escape opening and closing tags because you will get problems with the browser interpreting things incorrectly.</p>
<blockquote>
<pre>var ad_code = ad_code ? ad_code : '1a';
var referral_code = referral_code ? referral_code : '000';
var ad_width = ad_width ? ad_width : 200;

// switch code to see what we want to serve up
switch(ad_code){

   case '1a':
     document.write(unescape("%3Cdiv   style='width:"+ad_width+"px; font-family: verdana, arial, helvetica,   sans-serif; cursor:pointer; font-size:11px;'%3E"));
     document.write(unescape("%3Ca href='" + myHost + "kevindubois.com/index.php?  referral="+referral_code+"' style='text-decoration:none;color:white'%3E"));

     document.write(unescape("%3Cdiv style='border-top:5px solid #0F0442;   width:"+ad_width+"px; background-color:#FF6204; color:#FFF; padding-bottom:10px '%3E"));
     document.write(unescape("%3Cul%3E"));    
     document.write(unescape("%3Cli style='margin-left:-15px'%3EThis is a   demo for %3Ca href='http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites'%3E  http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites%3C/a%3E%3C/li%3E"));    
     document.write(unescape("%3Cli style='margin-left:-15px'%3bla bla bla%3C/li%3E"));    
     document.write(unescape("%3Cli style='margin-left:-15px'%3Ebla bla bla%3C/li%3E"));    
     document.write(unescape("%3Cli style='margin-left:-15px'%3Ebla bla bla%3C/li%3E"));    
     document.write(unescape("%3C/ul%3E  "));    
     document.write(unescape("%3Cdiv style='text-align:center;font-weight:bold;   font-size:12px; '%3E LEARN MORE %3C/div%3E"));    
     document.write(unescape("%3C/div%3E"));    
     document.write(unescape("%3C/a%3E"));    
     document.write(unescape("%3C/div%3E"));
   break;

   case '2a':
     document.write(unescape("%3Cdiv style='width:"+ad_width+"px; font-family:   verdana, arial, helvetica, sans-serif; cursor:pointer; font-size:11px;'%3E"));
     document.write(unescape("%3Ca href='" + myHost +   "kevindubois.com/index.php?referral="+referral_code+"' style='text-decoration:none;color:white'%3E"));

     document.write(unescape("%3Cdiv style='border-top:5px solid #0F0442;   width:"+ad_width+"px; background-color:#FF6204; color:#FFF; padding-bottom:10px '%3E"));
     document.write(unescape("%3Cul%3E"));    
     document.write(unescape("%3Cli style='margin-left:-15px'%3EThis is a demo for   %3Ca href='http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites'%3Ehttp://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites%3C/a%3E%3C/li%3E"));    
     document.write(unescape("%3Cli style='margin-left:-15px'%3bla bla bla%3C/li%3E"));    
     document.write(unescape("%3Cli style='margin-left:-15px'%3Ebla bla bla%3C/li%3E"));    
     document.write(unescape("%3Cli style='margin-left:-15px'%3Ebla bla bla%3C/li%3E"));    
     document.write(unescape("%3C/ul%3E  "));    
     document.write(unescape("%3Cdiv style='text-align:center;font-weight:bold;   font-size:12px; '%3E LEARN MORE %3C/div%3E"));    
     document.write(unescape("%3C/div%3E"));    
     document.write(unescape("%3C/a%3E"));    
     document.write(unescape("%3C/div%3E"));
   break;

   // and so on ...
}</pre>
</blockquote>
<p>The only thing I haven&#039;t mentioned is the links and the referral code: you can track widgets and clicks from each 3rd party by supplying a referral code. The link within the widget has this referral code and in the linked page you can then write some code to track/count/whatever you want.<br />
From here on, I think you should have all the tools to start customizing your own widget. You can make everything even more dynamic by using some ajax; you can add more parameters or really any content you want.</p>
<p>You can find a demo for the 2nd widget at <a title="widget2" href="http://www.kevindubois.com/demos/widget2.html" target="_blank">http://www.kevindubois.com/demos/widget2.html</a> (the js code is at <a title="widget1 javascript" href="http://www.kevindubois.com/demos/js/mywidget2.js" target="_blank">http://www.kevindubois.com/demos/js/mywidget2.js</a>)</p>
<p class="buymebeer"><form action="https://www.paypal.com/cgi-bin/webscr" target="paypal" method="post"><input type="hidden" name="cmd" value="_xclick" /><input type="hidden" name="business" value="kevin.dubois@gmail.com" /><input type="hidden" name="return" value="" /><input type="hidden" name="item_name" value="Buy Me a Beer for Creating an advertisement widget for external websites using JavaScript" /><input type="hidden" name="currency_code" value="USD" /><input type="hidden" name="amount" value="1" /><input type="image" src="http://kevindubois.com/blog/wp-content/plugins/buy-me-beer/icon_beer.gif" align="left" alt="" title="" hspace="3" /></form><a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&amp;business=kevin.dubois@gmail.com&amp;currency_code=USD&amp;amount=1&amp;return=&amp;item_name=Buy+Me+a+Beer+for+Creating+an+advertisement+widget+for+external+websites+using+JavaScript" target="paypal">Was this post helpful? Buy me a drink :-)</a></p>]]></content:encoded>
			<wfw:commentRss>http://kevindubois.com/blog/2009/11/16/creating-advertisement-widgets-for-3rd-party-websites/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rotating images using jQuery Ajax</title>
		<link>http://kevindubois.com/blog/2009/03/03/rotating-images-jquery-ajax/</link>
		<comments>http://kevindubois.com/blog/2009/03/03/rotating-images-jquery-ajax/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 23:20:21 +0000</pubDate>
		<dc:creator>Kevin Dubois</dc:creator>
				<category><![CDATA[ajax]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[slideshow]]></category>

		<guid isPermaLink="false">http://kevindubois.com/blog/?p=13</guid>
		<description><![CDATA[Tweet There are many ways to rotate images on a website.  In my case, I needed a way to rotate all images from a particular folder, and I wanted it so that I just have to dump images in the &#8230; <a href="http://kevindubois.com/blog/2009/03/03/rotating-images-jquery-ajax/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="border:1px solid #808080;background-color:#F0F4F9;">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fkevindubois.com%2Fblog%2F2009%2F03%2F03%2Frotating-images-jquery-ajax%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" style="border:none; overflow:hidden; width=85px; height:21px;"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://kevindubois.com/blog/2009/03/03/rotating-images-jquery-ajax/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://kevindubois.com/blog/2009/03/03/rotating-images-jquery-ajax/"  data-text="Rotating images using jQuery Ajax" data-count="horizontal">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://kevindubois.com/blog/2009/03/03/rotating-images-jquery-ajax/" data-counter="right"></script></div>			
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://kevindubois.com/blog/2009/03/03/rotating-images-jquery-ajax/"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><p>There are many ways to rotate images on a website.  In my case, I needed a way to rotate all images from a particular folder, and I wanted it so that I just have to dump images in the folder in order for the slideshow to pick them up.  ** NOTE: if you want a more advanced setup with database driven slides visit my <a title="Database driven jquery rotating slideshow demo" href="http://kevindubois.com/blog/2009/07/29/database-driven-jquery-rotating-slide-show-with-text-navigation-and-links-using-the-cycle-plugin/" target="_blank">post about database driven slideshows</a></p>
<p>For this tutorial I&#039;m going to use jQuery&#039;s framework and crossSlide, a plugin for jQuery which will allow smooth transitions between the images.  If you don&#039;t have it already, you can get jQuery at <a title="www.jquery.com" href="http://www.jquery.com" target="_blank">www.jquery.com</a> and the crossSlide plugin at <a title="www.gruppo4.com/~tobia/cross-slide.shtml" href="http://www.gruppo4.com/~tobia/cross-slide.shtml" target="_blank">www.gruppo4.com/~tobia/cross-slide.shtml</a> .  You&#039;ll also have to create a folder with images.  You&#039;ll get the best result if all images are identical in size.</p>
<p>A working example can be found at <a title="duboistechnologies.com" href="http://www.duboistechnologies.com">duboistechnologies.com</a> .</p>
<p>Download the code <a title="rotate images zip" href="http://kevindubois.com/blog/attachments/rotate_images.zip" target="_self">here</a></p>
<p>Ok, first things first: we&#039;ll need a placeholder for the images.  We&#039;ll need to specify a fixed height for this placeholder too, otherwise the content below will be jumping up and down every time a new image is loaded:</p>
<blockquote><p>&lt;div id=&#034;imgcontainer&#034; style=&#034;margin:0; width:46em; height:20em;&#034;&gt;<br />
&lt;img src=&#034;img/ajax-loader.gif&#034; style=&#034;margin-top:20%&#034; alt=&#034;loading&#8230;&#034; id=&#034;mainImg&#034; /&gt;<br />
&lt;/div&gt;</p></blockquote>
<p>I put an image in the div that will show an icon while the images are loaded&#8230;</p>
<p>Next step is to create a php page with some code to get all images from the folder.   The getfiles function will get all files and return a string that will be formatted so it can be parsed as separate objects by the javascript eval() function&#8230; but that&#039;s for later.  We just echo this string so our ajax call will pick it up.  The only thing you&#039;ll need to customize is the &#039;imagefolder&#039;&#8230; change this to whatever the name or path is to your folder:</p>
<blockquote><p>&lt;?php</p>
<p>echo getfiles(&#039;imagefolder&#039;);</p>
<p>function getfiles($folder=&#034;, $extensions=&#039;.*&#039;)<br />
{</p>
<p>// path:<br />
$folder = trim($folder);<br />
$folder = ($folder == &#034;) ? &#039;./&#039; : $folder;</p>
<p>// validate folder<br />
if (!is_dir($folder)){ die(&#039;invalid folder given!&#039;); }</p>
<p>// create files array<br />
$files = array();</p>
<p>// open directory<br />
if ($dir = @opendir($folder)){</p>
<p>// get all files:<br />
while($file = readdir($dir)){</p>
<p>if (!preg_match(&#039;/^\.+$/&#039;, $file) and<br />
preg_match(&#039;/\.(&#039;.$extensions.&#039;)$/&#039;, $file)){</p>
<p>// feed the array:<br />
$files[] = $file;<br />
}<br />
}<br />
// close directory<br />
closedir($dir);<br />
}<br />
else {<br />
die(&#039;Could not open the folder &#034;&#039;.$folder.&#039;&#034;&#039;);<br />
}</p>
<p>if (count($files) == 0){<br />
die(&#039;No files where found <img src='http://kevindubois.com/blog/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> &#039;);<br />
}<br />
// shuffle the array so we have a random sequence of images<br />
shuffle($files);</p>
<p>$return = &#034;;<br />
foreach($files as $file){<br />
// format the string so we can later parse it into objects in javascript<br />
$return .= &#034;{&#039;src&#039;:'{$folder}/{$file}&#039;},&#034;;<br />
}<br />
$return = &#034;[".substr($return, 0,-1)."]&#034;;</p>
<p>// return the string:<br />
return $return;</p>
<p>}</p>
<p>?&gt;</p></blockquote>
<p>What we need to do now is set up an ajax call that gets the string of images the above function found in my images folder.  We&#039;ll also have to include the jquery and crossSlide packages:</p>
<blockquote><p>&lt;script type=&#034;text/javascript&#034; src=&#034;js/jquery.js&#034;&gt;&lt;/script&gt;<br />
&lt;script type=&#034;text/javascript&#034; src=&#034;js/jquery.cross-slide.js&#034;&gt;&lt;/script&gt;</p>
<p>&lt;script type=&#034;text/javascript&#034;&gt;<br />
$(document).ready(function(){loadImage();})</p>
<p>function loadImage(){<br />
// getimage.php is the php file that gets my images from the images folder<br />
$.post(&#034;getimage.php&#034;, function(data){<br />
if(data.length &gt;0) {<br />
// evaluate the string to a group of objects<br />
myObject = eval(data);<br />
// create a slideshow with the image objects and drop them in the placeholder<br />
$(&#039;#imgcontainer&#039;).crossSlide({sleep:5,fade:2},myObject);<br />
}<br />
});</p>
<p>}<br />
&lt;/script&gt;</p></blockquote>
<p>That&#039;s all there is to it.  This is a great alternative to flash and is much less cpu intensive!</p>
<p class="buymebeer"><form action="https://www.paypal.com/cgi-bin/webscr" target="paypal" method="post"><input type="hidden" name="cmd" value="_xclick" /><input type="hidden" name="business" value="kevin.dubois@gmail.com" /><input type="hidden" name="return" value="" /><input type="hidden" name="item_name" value="Buy Me a Beer for Rotating images using jQuery Ajax" /><input type="hidden" name="currency_code" value="USD" /><input type="hidden" name="amount" value="1" /><input type="image" src="http://kevindubois.com/blog/wp-content/plugins/buy-me-beer/icon_beer.gif" align="left" alt="" title="" hspace="3" /></form><a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&amp;business=kevin.dubois@gmail.com&amp;currency_code=USD&amp;amount=1&amp;return=&amp;item_name=Buy+Me+a+Beer+for+Rotating+images+using+jQuery+Ajax" target="paypal">Was this post helpful? Buy me a drink :-)</a></p>]]></content:encoded>
			<wfw:commentRss>http://kevindubois.com/blog/2009/03/03/rotating-images-jquery-ajax/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		</item>
		<item>
		<title>Adding additional text fields with Javascript</title>
		<link>http://kevindubois.com/blog/2008/10/16/adding-additional-text-fields-with-javascript/</link>
		<comments>http://kevindubois.com/blog/2008/10/16/adding-additional-text-fields-with-javascript/#comments</comments>
		<pubDate>Thu, 16 Oct 2008 16:11:46 +0000</pubDate>
		<dc:creator>Kevin Dubois</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[html]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://kevindubois.com/blog/?p=3</guid>
		<description><![CDATA[Tweet ** UPDATE: This functionality is outdated. Look at a more recent post on how to add more field to a form field: &#039;Add More&#039; form fields with javascript / jquery ** One of my clients needed the ability for &#8230; <a href="http://kevindubois.com/blog/2008/10/16/adding-additional-text-fields-with-javascript/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="bottomcontainerBox" style="border:1px solid #808080;background-color:#F0F4F9;">
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fkevindubois.com%2Fblog%2F2008%2F10%2F16%2Fadding-additional-text-fields-with-javascript%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" style="border:none; overflow:hidden; width=85px; height:21px;"></iframe></div>
			<div style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<g:plusone size="medium" href="http://kevindubois.com/blog/2008/10/16/adding-additional-text-fields-with-javascript/"></g:plusone>
			</div>
			<div style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;">
			<a href="http://twitter.com/share" class="twitter-share-button" data-url="http://kevindubois.com/blog/2008/10/16/adding-additional-text-fields-with-javascript/"  data-text="Adding additional text fields with Javascript" data-count="horizontal">Tweet</a>
			</div><div style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://kevindubois.com/blog/2008/10/16/adding-additional-text-fields-with-javascript/" data-counter="right"></script></div>			
			<div style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://kevindubois.com/blog/2008/10/16/adding-additional-text-fields-with-javascript/"></script></div>			
			</div><div style="clear:both"></div><div style="padding-bottom:4px;"></div><p>** UPDATE: This functionality is outdated.  Look at a more recent post on how to add more field to a form field:<br />
<a href="http://kevindubois.com/blog/2011/10/24/add-more-form-fields-with-javascript-jquery/">&#039;Add More&#039; form fields with javascript / jquery</a> **</p>
<p>One of my clients needed the ability for users to refer their family and friends to the website by sending them an email.   The idea was to have 5 fixed fields, and the ability to add more fields on the fly before hitting submit.</p>
<p><strong>Step 1</strong> is obviously adding the static html code (with a tiny bit of php to avoid redundancy):</p>
<blockquote><p>&lt;form action=&#034;mysubmitpage.php&#034; method=&#034;post&#034;&gt;<br />
&lt;div id=&#039;fields&#039;&gt;<br />
&lt;? for($i=1; $i&lt;6; $i++){?&gt;<br />
&lt;div&gt;<br />
name: &lt;input type=&#034;text&#034; name=&#034;refname&lt;?=$i?&gt;&#034; /&gt;</p>
<p>email: &lt;input type=&#034;text&#034; name=&#034;refemail&lt;?=$i?&gt;&#034;  /&gt;</p>
<p>&lt;/div&gt;<br />
&lt;? }?&gt;</p>
<p>&lt;/div&gt;</p>
<p>&lt;div style=&#034;margin-top:5px;&#034;&gt;<br />
&lt;input type=&#034;submit&#034; value=&#034;Send Invitations&#034; name=&#034;send&#034; /&gt;<br />
&lt;/div&gt;</p>
<p>&lt;/form&gt;</p></blockquote>
<p><strong>Step 2</strong> involves adding an &#039;add more&#039; link, which calls the javascript function that adds the field.  I&#039;m passing the number of the next field into the function, so when the time comes to submit it to the server I can distinguish the fields.  I would have preferred to use IE&#039;s outerHTML but that&#039;s not supported in my preferred browser firefox, so to keep everything neat I get the existing fields and append the new field to the end of the string.   I also replace the &#034;add more&#034; link so next time it is clicked the number 7, 8, 9 etc is passed.</p>
<blockquote><p>&lt;script language=&#034;javascript&#034;&gt;<br />
function addrefField(i){<br />
var newfieldContent = &#034;&lt;div&gt;name: &lt;input type=\&#034;text\&#034; name=\&#034;refname&#034;+i+&#034;\&#034; /&gt; email: &lt;input type=\&#034;text\&#034; name=\&#034;refemail&#034;+i+&#034;\&#034; /&gt; &lt;/div&gt; \n&#034;;</p>
<p>var oldfieldContent = document.getElementById(&#039;fields&#039;).innerHTML;</p>
<p>el = document.getElementById(&#039;fields&#039;);<br />
el.innerHTML = oldfieldContent + newfieldContent;</p>
<p>x = i + 1;<br />
var addmoreContent = document.getElementById(&#039;addmorelink&#039;);<br />
addmoreContent.innerHTML = &#039;&lt;div&gt;&lt;a href=&#034;javascript:addrefField(&#039;+x+&#039;)&#034;&gt;add more&lt;/a&gt;&lt;/div&gt;&lt;input type=&#034;hidden&#034; name=&#034;numberfields&#034; value=&#034;&#039;+i+&#039;&#034; /&gt;&#039;;</p>
<p>}</p>
<p>&lt;/script&gt;</p>
<p>&lt;div id=&#039;addmorelink&#039;&gt;<br />
&lt;a href=&#034;javascript:addrefField(6)&#034;&gt;add more&lt;/a&gt;<br />
&lt;input type=&#034;hidden&#034; name=&#034;numberfields&#034; value=&#034;6&#034; /&gt;<br />
&lt;/div&gt;</p></blockquote>
<p><strong>Step 3 </strong>: The above code seems to work fine in IE, but in Firefox there is a problem: the value of the existing fields is reset to whatever the DOM originally served up to the user.  So if the user had started to fill out the fields and then clicked the &#039;add more&#039; link, all fields would have been emptied.  With every problem comes a solution ofcourse.  I googled my problem and stumbled upon <a title="this post" href="http://dev-answers.blogspot.com/2007/08/firefox-does-not-reflect-input-form.html" target="_blank">this post</a>.  By adding a function (updateDOM()) on the onBlur event for each field, we can update the DOM to reflect the already inserted values.  So here&#039;s the entire code for the form:</p>
<blockquote><p>&lt;script language=&#034;javascript&#034;&gt;<br />
function addrefField(i){<br />
var newfieldContent = &#034;&lt;div&gt;name: &lt;input type=\&#034;text\&#034; name=\&#034;refname&#034;+i+&#034;\&#034; onBlur=\&#034;updateDOM(this)\&#034; /&gt; email: &lt;input type=\&#034;text\&#034; name=\&#034;refemail&#034;+i+&#034;\&#034; onBlur=\&#034;updateDOM(this)\&#034; /&gt; &lt;/div&gt; \n&#034;;</p>
<p>var oldfieldContent = document.getElementById(&#039;fields&#039;).innerHTML;</p>
<p>el = document.getElementById(&#039;fields&#039;);<br />
el.innerHTML = oldfieldContent + newfieldContent;</p>
<p>x = i + 1;<br />
var addmoreContent = document.getElementById(&#039;addmorelink&#039;);<br />
addmoreContent.innerHTML = &#039;&lt;div&gt;&lt;a href=&#034;javascript:addrefField(&#039;+x+&#039;)&#034;&gt;add more&lt;/a&gt;&lt;/div&gt;&lt;input type=&#034;hidden&#034; name=&#034;numberfields&#034; value=&#034;&#039;+i+&#039;&#034; /&gt;&#039;;</p>
<p>}</p>
<p>function updateDOM(inputField) {<br />
// if the inputField ID string has been passed in, get the inputField object<br />
if (typeof inputField == &#034;string&#034;) {<br />
inputField = document.getElementById(inputField);<br />
}</p>
<p>if (inputField.type == &#034;select-one&#034;) {<br />
for (var i=0; i&lt;inputField.options.length; i++) {<br />
if (i == inputField.selectedIndex) {<br />
inputField.options[inputField.selectedIndex].setAttribute(&#034;selected&#034;,&#034;selected&#034;);<br />
}<br />
}<br />
} else if (inputField.type == &#034;text&#034;) {<br />
inputField.setAttribute(&#034;value&#034;,inputField.value);<br />
} else if (inputField.type == &#034;textarea&#034;) {<br />
inputField.setAttribute(&#034;value&#034;,inputField.value);<br />
} else if ((inputField.type == &#034;checkbox&#034;) || (inputField.type == &#034;radio&#034;)) {<br />
if (inputField.checked) {<br />
inputField.setAttribute(&#034;checked&#034;,&#034;checked&#034;);<br />
} else {<br />
inputField.removeAttribute(&#034;checked&#034;);<br />
}<br />
}<br />
}</p>
<p>&lt;/script&gt;</p>
<p>&lt;form action=&#034;index.php&#034; method=&#034;post&#034;&gt;<br />
&lt;div id=&#039;fields&#039;&gt;<br />
&lt;? for($i=1; $i&lt;6; $i++){?&gt;<br />
&lt;div&gt;<br />
name: &lt;input type=&#034;text&#034; name=&#034;refname&lt;?=$i?&gt;&#034; onBlur=&#034;updateDOM(this)&#034; /&gt; email:<br />
&lt;input type=&#034;text&#034; name=&#034;refemail&lt;?=$i?&gt;&#034; onBlur=&#034;updateDOM(this)&#034; /&gt; &lt;/div&gt;<br />
&lt;? }?&gt;</p>
<p>&lt;/div&gt;<br />
&lt;div id=&#039;addmorelink&#039;&gt;<br />
&lt;a href=&#034;javascript:addrefField(6)&#034;&gt;add more&lt;/a&gt;<br />
&lt;input type=&#034;hidden&#034; name=&#034;numberfields&#034; value=&#034;6&#034; /&gt;<br />
&lt;/div&gt;<br />
&lt;div style=&#034;margin-top:5px;&#034;&gt;   &lt;input type=&#034;submit&#034; value=&#034;Send Invitations&#034; name=&#034;send&#034; /&gt; &lt;/div&gt;</p>
<p>&lt;/form&gt;</p></blockquote>
<p><strong>Step 4</strong> : All that&#039;s left is processing the fields on the next page:</p>
<blockquote><p>&lt;?php</p>
<p>$loops = $_POST['numberfields'];<br />
for($i=1;$i&lt;=$loops;$i++){</p>
<p>$namepost = &#034;refname&#034; . $i;<br />
$name = $_POST[$namepost];<br />
$emailpost = &#034;refemail&#034; . $i;<br />
$email = $_POST[$emailpost];<br />
if($name &amp;&amp; $email){<br />
echo $name .&#039; &#039; .$email;<br />
echo &#039;&lt;br /&gt;&#039;;<br />
}</p>
<p>}</p>
<p>?&gt;</p></blockquote>
<p class="buymebeer"><form action="https://www.paypal.com/cgi-bin/webscr" target="paypal" method="post"><input type="hidden" name="cmd" value="_xclick" /><input type="hidden" name="business" value="kevin.dubois@gmail.com" /><input type="hidden" name="return" value="" /><input type="hidden" name="item_name" value="Buy Me a Beer for Adding additional text fields with Javascript" /><input type="hidden" name="currency_code" value="USD" /><input type="hidden" name="amount" value="1" /><input type="image" src="http://kevindubois.com/blog/wp-content/plugins/buy-me-beer/icon_beer.gif" align="left" alt="" title="" hspace="3" /></form><a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&amp;business=kevin.dubois@gmail.com&amp;currency_code=USD&amp;amount=1&amp;return=&amp;item_name=Buy+Me+a+Beer+for+Adding+additional+text+fields+with+Javascript" target="paypal">Was this post helpful? Buy me a drink :-)</a></p>]]></content:encoded>
			<wfw:commentRss>http://kevindubois.com/blog/2008/10/16/adding-additional-text-fields-with-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

