Dynamic form elements & the jQuery validation plugin

I recently run into a problem where I had to validate a form with dynamic fields. I am impressed of the jQuery Validation plugin but I had no clue on how to achieve this as the documentation does not have any code on this included. A few searches on in the WWW didn’t bring the right results, but I eventually found some snippet in the Google Groups (I forgot where, sorry).

Now, let’s say you have a form with a few elements and depending on their selection or values one or more fields are added to the form:

View a basic sample/demo form here

Since you cannot validate a hidden element (because the user can’t make a selection or enter anything), you cannot add validation rules. You need to add/remove this rules dynamic depending on the user’s input.

Actually, the code is very simple. All you have to do is to catch the ‘change’, ‘blur’ or whatever event from the ‘other’ element and attach a simple function to add the validation rule. To go with the demo form this is it:

1
2
3
4
5
6
7
8
9
10
11
12
13
jQuery( jQuery("input[name='howhelp']") ).change( function()
{
  if ( jQuery("input[name='howhelp']:checked" ).val() == "help" )
  {
    jQuery("#whathelp").rules("add", "required");
    jQuery("#problems").show();
  }
  else
  {
    jQuery("#whathelp").rules("remove", "required");
    jQuery("#problems").hide();
  }
});

Simple. Let’s see what the code does line for line:

  • line 1 tells to fire a function if the radiobuttons status have changed
  • line 3 checks if the current selected radiobutton’s value is equal to ‘help’
  • line 5 adds the validation rule to the hidden select ‘whathelp’
  • line 6 shows the hidden select
  • the rest removes the validation rule and hides the select, in this case the value was not equal to ‘help’

With this code, you can validate pretty much any complex form with the validate plugin.

Further reading:

I’d like to know how you validate complex dynamic forms, so please leave your comments here.

Too Busy

As you already have seen, I am currently absolutely not able to keep up with my Blog. I’ve been sick for weeks, have too many tasks and jobs to complete and I’m in the process of opening a new Restaurant/Bar/Guesthouse. In short: I have no clue when I’m back here on my virtual home.

iF AJAX Comments For WordPress – can you do it?

I also wasn’t able to keep up with the development of my plugin and unlikely will be able to update it within the coming weeks, so I made a decision:

If anyone wants to take over further development of the plugin, you are free to do so. There will be no support from my side. Contact me if you think you are able do it.

That’s about it for the moment. I wish everyone a happy and successful 2009!

iF AJAX Comments For WordPress: Latest Beta Version

For those who can’t wait or want to test the upcoming version, here’s the latest beta. Tested in WP 2.7 RC1 with the default theme.

Known issues

  • The new comment threading function in WP 2.7 is not yet supported (the comment is added at the wrong location)

Download

iF AJAX Comments For WordPress 0.99.5b

Have fun!

Quick Progress Note And A Few Links

This is just a qick note & response to Gene’s question ‘Any progress on a 2.7 compatible version now that there are public betas out there?’.

I already made some changes to the plugin to make it work with the new comments template of WP 2.7, but it is still buggy. Once the bugs are cleaned out I will of course upload the changes for you all. WP 2.7 is soon to be released and I think that I will have time this coming weekend to work on the plugin. So, hopefully, next Sunday or Monday there will be a new version to grab & enjoy for you.

Today I found some useful links on Digg which I would like to share with you:

Enjoy!

Site Updates, My Plugin And Other News

It’s time for some updates:

Site Updates

  • I switched from ‘i.Farang’ to ‘Flowdrops’
    I have made this change because I want the focus of the site to be more on my work & ideas rather than my private life and other uninteresting things. I also switched to a temporary theme because WP 2.7 has broken many things on the site. I wanted to change the theme anyway, but not before 2009 (stay tuned, something cool is coming!)
  • I deactivated my Plugin ‘iF AJAX Comments for WordPress’
    simple reason: WP 2.7 – it breaks the plugin and I’m working on a update. It takes a little longer than expected, I just want to make sure that all new commenting features of WP 2.7 are supported. There are also a few spam plugins of which my plugin didn’t play nice. Same here: stay tuned

My Plugin

WordPress 2.7 breaks my plugin ‘iF AJAX Comments for WordPress’! This is not something to worry about, there are just some changes in the comments template because of the threading and paging features which comes with the new WP version. The diffictult part is the threading function: the form jumps around in the comment thread but the posted comment is currently inserted at the bottom of the list. No problem though, I’ll get this done. It’s also a good opportunity for me to further optimize and clean up my code. I also like to integrate a function which makes the plugin compatible for all the themes which are using only DIVs to list the comments. Furthermore, there are still some compatibility issues with various spam plugins. I want to have all this done before releasing a new version, so: stay tuned!

Other things to take note

I recently made some good connections here in Thailand and over the Internet and currently getting some good projects. Means I’m a little bit busy this time but that’s good. I like being busy. The bad part is that I have not much time to take care of this site and post some good quality stuff. Everything should become normal again within the next two months. Until then: stay tuned!

Automattic Acquired IntenseDebate’s Enhanced Comment System

According to this news, as well as this one and this blog post at IntenseDebate, Automattic has aquired the enhanced comment system of IntenseDebate. The coming WordPress 2.7 will include some of IntenseDebate’s features by default, including threaded commenting.

IntenseDebate originally launched to the public last October, sporting features including OpenID support, user profiles, and the ability to track a user’s comments across multiple blogs.

This will probably be the end of my plugin, iF AJAX Comment for WordPress. I already had a feeling that this could happen, I commented about it. When WordPress 2.7 is out, we’ll see what’s still missing.

More about the aquisition:

Guest Posts And the_author() In Your WordPress Blog

As you may have seen I have a guest post on this blog written by Matt from phuketvogue.com. Since I am the only registered writer/author on this site, all posts are marked as ‘written by Toxane’ or something similar. I thought it would be just fair for the guest writer, to mark these posts with the corresponding author name and a link back to the author’s site.

What I didn’t want was to have the guest authors as registered WordPress users on my blog, just to keep things simple (and save). I came up with the following solution:

In my theme folder I have my ‘functions.php’ file and I added the following code to it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Guest Posts
function theAuthor()
{
	$guestName = get_post_custom_values("guestName");
	$guestLink = get_post_custom_values("guestLink");
 
	if ($guestName)
	{
		if ($guestLink)
		{
			echo '<a href="'.$guestLink[0].'" target="_blank">'.$guestName[0].'</a>';
		}
		else
		{
			echo $guestName[0];
		}
	}
	else
	{
		the_author();
	}
}

The code checks if the post has a custom field ‘guestName’. If the field is found, the code further checks if there’s a custom field ‘guestLink’. If that field is found as well, the code returns the name of the guest author as a hyperlink back to the guest authors website. If there’s no ‘guestLink’, only the guest author’s name is returned. If both custom fields are missing, the code returns ‘the_author()’ which is the registered WordPress user.

Next I replaced all occurences of ‘the_author()’ in the theme files with ‘theAuthor()’

To mark any post in your WordPress Blog as a guest post, you just add a custom field ‘guestName’ and the name of the guest author as value. If you want the guest author’s name appears as a hyperlink, just add a custom field ‘guestLink’ and the web address of the guest author as value.

That’s it. Simple and fair for your guest author(s).

WordPress, My Gravatar and the Mystery Man

Mystery Man - the default Gravatar

Mystery Man - the default Gravatar

I just had a problem with my own gravatar not showing up on my own site for the comments I wrote. First I thought that clearing the browser cache would solve everything. I was wrong. After clearing the cache, deleting cookies and checking my gravatar (http://en.gravatar.com/site/check/), I was really out of (quick) ideas. Then it suddenly hit me: a few days ago I changed a few things in my Blog’s user accounts. I added new accounts with different user rights and merged the old accounts with the new ones.

After having a look at WordPress’s gravatar code (wp-includes/pluggable.php), everything was clear: WordPress actually pulls the user id and gets the email address which is stored in the user account data for this id. This ensures that if a user changes the email address in the user account, it will always pull the new gravatar associated with the new email address. The user id – for registered users – is stored in the comments table for each and every comment.

That said, if you change user accounts and a user id changes, you need to run

UPDATE wp_comments SET user_id = new_user_id WHERE user_id = old_user_id

otherwise you’re going to have a lot comments from the mystery man…

PayPal donation form with CSS and jQuery for WordPress

Yesterday I got an email from Jamie asking me how I made my PayPal donation form. Here’s how I did it.

First, we need a PayPal form with the donation stuff inside:

1
2
3
4
5
6
7
8
9
10
11
12
<form id="form_paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">
  <input type="hidden" name="cmd" value="_donations">
  <input type="hidden" name="business" value="paypal@email.com">
  <input type="hidden" name="item_name" value="My Donations Subject">
  <input type="hidden" name="no_shipping" value="0">
  <input type="hidden" name="no_note" value="1">
  <input type="hidden" name="currency_code" value="USD">
  <input type="hidden" name="tax" value="0">
  <input type="hidden" name="bn" value="PP-DonationsBF">
  <label for="">Amount (US$) : </label><input type="text" name="amount" id="input_amount" width="10" class="text" />
  <input type="submit" name="submit" value="Donate" class="submit" />
</form>

More information about the PayPal donation buttons and the form code behind can be found here: https://www.paypal.com/cgi-bin/webscr?cmd=_pdn_donate_techview_outside

Next, we need to add some more code to the form where we want to show the various messages displayed by jQuery. These messages are set to be hidden (display:none;):

1
2
3
4
<input type="submit" name="submit" value="Donate" class="submit" />&nbsp;&nbsp;
<span id="msg_moreamount" class="icon_warning red" style="display:none;">PayPal takes $0.35 commission for a $1 donation. Please enter at least $1.35 , thank you!</span>
<span id="msg_noamount" class="icon_warning red" style="display:none;">Please enter the amount you wish to donate and try again.</span>
<span id="msg_activity" style="display:none;"> <img src="images/loader.gif" align="absmiddle" />&nbsp;Transferring to PayPal, please wait...</span>

The jQuery script which actually checks and validates the form looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
jQuery(document).ready(function()
{
	// the minimum required value to be entered.
	// in this case PayPal takes $0.35 from a $1
	// donation, hence we ask for at least $1.35
	var minimum_value = 1.35;
 
	// attach this script to the form's submit action
	jQuery('#form_paypal').submit(function()
	{
		// check if there is an amount entered
		if (jQuery('#input_amount').val() > null)
		{
			// is the amount equal to or higher than the minimum_value?
			if (jQuery('#input_amount').val() < minimum_value)
			{
				// need more amount
				// hide messages, show more amount error
				jQuery('#msg_noamount').hide();
				jQuery('#msg_moreamount').fadeIn();
				return false; // prevent the form from submitting
			}
			else
			{
				// amount is more than minimum_value
				// hide messages, show activity
				jQuery('#msg_moreamount').hide();
				jQuery('#msg_noamount').hide();
				jQuery('#msg_activity').fadeIn();
				return true; // submit the form
			}
		}
		else
		{
			// no amount entered at all
			// hide messages, show no amount error
			jQuery('#msg_moreamount').hide();
			jQuery('#msg_noamount').fadeIn();
			return false; // prevent the form from submitting
		}
	});
});

The code is documented so it should be clear what each block does.

The final step is to add some CSS styling:

1
2
3
4
5
.red {color:#ff0000;}
.icon_warning {background:transparent url(../images/exclamation.png) left no-repeat;padding:4px;padding-left:20px;}
form#form_paypal input {padding:3px;border:1px solid #ddd;background:#fefefe;}
form#form_paypal input#input_amount {width:50px;}
form#form_paypal .submit {cursor:pointer;border-style:outset;}

If you want to integrate this form into your WordPress Blog then this is the way to go:

In your WordPress Theme folder (wp-content/themes/yourtheme/) create a new file named ‘donate.php’. To make the file available as a WordPress page template you’ll need to add the following code at the top of the file:

1
2
3
4
5
<?php
/*
Template Name: Donate
*/
?>

A donation form template for the default theme would look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
/*
Template Name: Donate
*/
?>
<?php get_header(); ?>
<div id="content" class="narrowcolumn">
  <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
  <div class="post" id="post-<?php the_ID(); ?>">
    <h2>Make A Donation</h2>
    <p>If you think you have benefited or I have helped you in some way, by using any of my 
    WordPress plugins or themes, please consider making a donation. Donations support the 
    continued development of my websites and help cover the hosting costs. 
    Donations of any size are gratefully accepted. Thank you!</p>
    <form id="ppDonate" action="https://www.paypal.com/cgi-bin/webscr" method="post">
      <input type="hidden" name="cmd" value="_donations">
      <input type="hidden" name="business" value="paypal@email.com">
      <input type="hidden" name="item_name" value="My Donations Subject">
      <input type="hidden" name="no_shipping" value="0">
      <input type="hidden" name="no_note" value="1">
      <input type="hidden" name="currency_code" value="USD">
      <input type="hidden" name="tax" value="0">
      <input type="hidden" name="bn" value="PP-DonationsBF">
      <label for="">Amount (US$) : </label>
      <input type="text" name="amount" id="ppAmount" width="10" class="text" />
      <input type="submit" name="submit" value="Donate" class="submit" />
      <span id="moreAmount" class="warningIcon red" style="display:none;">PayPal takes $0.35 commission for $1 donation. 
      Please enter at least $1.35 , thank you!</span>
      <span id="noAmount" class="warningIcon red" style="display:none;">Please enter an amount to donate and try again.</span>
      <span id="ppGo" style="display:none;">
      <img src="&lt;?php bloginfo('template_url'); ?&gt;/images/loader.gif" align="absmiddle" />Transferring to PayPal, please wait...</span>
    </form>
    <p><small>Info : once you click on 'Donate', you will be transferred to PayPal where you can enter your payment information.</small></p>
  </div>
  <?php endwhile; endif; ?>
  <?php edit_post_link('Edit this entry.', '<p>', '</p>'); ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

Next you need to create a page in WordPress, call it ‘Donate’, ‘Make A Donation’ or whatever you want the page title to be. You can leave the page content empty as we will use our template file. Scroll down to the ‘Page Template’ section and select your page template (’Donate’ in our case). Save & publish the page.

Available Files

 

Hopefully this short tutorial will be of some use for you (if so, don’t forget to donate ;) ) and if you still have some questions feel free to leave a comment below.

Received Donations

Thank You!

 

Is Woopra worth the Hype?

I was having a look at another web site’s page source and I was wondering about a script tag in its footer. This is how I found Woopra. ‘Woopra is the world’s most comprehensive, information rich, easy to use, real-time Web tracking and analysis application.’ states the frontpage of Woopra’s web site. Ok, I’ll give it a shot.

When I registered my Woopra account, I almost instantly got a email with the registration confirmation link. ‘Cool’ was my thought, ‘now I’m checking out how feature rich this thing is’. After registration, you have to add a web site profile. I did that and was checking my mail account every few hours for the approval confirmation. After several hours and no response I got a little nervous and went to the Woopra Forums to check out if there’s something about the approval time. Indeed, there are quite many topics about the site approvals. This made me ‘a little’ pissed because they haven’t stated this anywhere. Just a line like ‘during beta, it may take several weeks to get your web site approved for Woopra ‘ or something like that would have make things clear. Ok, I’ll wait.

8 days later my site got approved. Fired up the Woopra Client and was quite impressed by the UI (User Interface). Several days and X tests later I feel that Woopra is not really worth the hype. There are only a few features which makes Woopra different from other statistic app’s: the rich user interface, the real time analytics and the proactive chat function. I have the real time analytics with my PMetrics account, don’t need the proactive chat function (and I personally hate it when I get interrupted by those marketing assistants or whoever while browsing a site) and for the rich UI, there’s something in the pipe: Google Analytics AIR (Screenshots)

Beside all that, the collected statistic results were far away from my other stats software (AWStats, Webalizer, Google Analytics and PMetrics).

Woopra’s competitors do not sleep and I think we can expect some new things soon. Time will tell.

Further readings: