Add Focus To HTML Forms

When you visit Google.com, you probably noticed that the mouse cursor jumps to the searchbox, ready for users to type and submit a search. This method is called form focus. It’s made possible by using Javascript. With Javascript, you can set certain elements of the HTML form to be set in focus. This is particularly helpful for pages where there is minimal content, and the intent of the web developer/designer is to get the user to enter data and submit quickly. A login page is a perfect example of such a page.

You can bring into focus the username field, so users can start typing their login credentials. The form focus saves users from finding the mouse cursor on the screen, and then clicking on the field. With form focus, users are already on the form, ready to input text and submit. If the user presses Tab, the cursor jumps to the next field, which happens to be the password field. Pressing Enter, simply submits the form to start the login process. This article will show you the most simple way to add form focus to your HTML forms. Consider a login page. It has two fields: username, password, and a Submit button. The HTML markup is:

<form method="post' action="submit.php">
<label for="username">Username: </label>
<input type="text" name="username" />
<label for="password">Password: </label>
<input type="password" name="password" />
<input type="submit" name="submit" value="Login" />
</form>

How To Add Focus To Forms

1. Assign an ID to the form. We are using an id of “login” in this example.

<form id="login" method='post' action="submit.php">

2. Add IDs to the fields.

<input id= "user" type="text"  name="username" />
<input id= "pass" type="password" name="password" />

3. Add Tab Index to the fields. Notice the order starting with 1 and then 2.

<input id= "user" type="text" name="username" tabindex="1" />
<input id= "pass" type="password" name="password" tabindex="2" />

4. Add Javascript at the end of the form.

<script type=”text/javascript” language=”JavaScript”>
document.login.user.focus();
</script>

Where login is the id of the form, and user is the id of the field.

Final Form

<form id="login" method="post" action="submit.php">
<label for="username">Username: </label>
<input id="user" type="text" name="username" tabindex="1" />
<label for="password">Password: </label>
<input id="pass" type="password" name="password" tabindex="2" />
<input type="submit" name="submit" value="Login" />
</form>
<script type="text/javascript" language="JavaScript">
document.login.user.focus();
</script>

This is just one way of adding form focus to HTML forms. There are other methods, like using body onload and such, but I find this method the cleanest and the most simple one to implement by far.

CodeIgniter Form_Dropdown

I had a little problem using CodeIgniter’s form_dropdown the other day. Form_dropdown produces an output similar to HTML’s form select option. I was trying to retrieve data queried from a database and display the result in a form. Well, after several test and trials, I finally got the script to work. Here’s how I did it.

Form_Dropdown

The form_dropdown function typically has 3 options. The first option is the fieldname. The second option is the option data usually laid out in an array. The third is the selected data.

form_dropdown(‘name’, array(1?=>’one’,2?=>’two’,3?=>’three’),1);

This produces:

<select name=’name’>
<option value=”1? selected=”selected”>One</option>
<option value=”2?>Two</option>
<option value=”3?>Three</option>
</select>

CodeIgniter

In CodeIgniter, I have a simple script that stores bookmarks. I categorize my bookmarks using tags. When adding bookmarks, I call on the get_dropdown_tags function in Models to retrieve all the tags and display them in array that I can use with form_dropdown. Here are my CodeIgniter entries.

Controller:

$data['tags'] = $this-&gt;links_model-&gt;get_dropdown_tags();

Models:

function get_dropdown_tags() {
  $tags = $this-&gt;db-&gt;query('select distinct tag from links');
  $dropdowns = $tags-&gt;result();
  foreach ($dropdowns as $dropdown) {
    $dropdownlist[$dropdown-&gt;tag] = $dropdown-&gt;tag;
  }
  $finaldropdown = $dropdownlist;
  return $finaldropdown;
}

Views:

In views, I’m simply calling the form_dropdown function using the $tags array passed on by the controller. It’s a pretty neat way to recall data from a database and outputting them in form_dropdown.

<?=form_dropdown(‘tag’,$tags);?>

Finally, a dropdown list that works.

Adding Javascript Confirmation To Forms

One feature worth implementing when designing websites is to add confirmation to forms. A simple popup message saying “Are you sure?” can greatly enhanced the user experience. It gives users a chance to confirm or escape out of a certain function. This is particularly feature is valuable after users click the Save, Delete or Submit button.

Unfortunately, both HTML and PHP languages lack the feature to add confirmation to forms. We turn our attention to Javascript the popup confirmation message we need in our forms. Below, you will see a simple, plain vanilla, submit button inside a HTML form.

HTML Form

<input type="Submit" name="submit" value="Submit" />

To add a confirmation to our submit button, we will use Javascript’s onclick event to detect if the input object has been clicked. Here’s how we add the onclick event in our simple form.

<input type="Submit" name="submit" value="Submit"
onclick="return confirmation();" />

Javascript Confirmation

Where’s our Javascript function? Well, here it is. Now that we have added the onclick event to our submit button, we will now add our Javascript function that you can place anywhere on your page. Here it is:

<script>
function confirmation()
{
var answer = confirm("Are you sure?")
 if (answer)
 {
  return true;
 } else {
  if (window.event) // True with IE, false with other browsers
  {
   window.event.returnValue=false; //IE specific
  } else {
   return false
  }
 }
}
</script>

The if statement with window.event is for the IE browser since it doesn’t play nice like the other browsers. You can call the Javascript function multiple times on the same page every time you need a popup confirmation. So there you have it, a simple popup confirmation you can add to your forms.

Sanitize Your Input In PHP

Here’s a quick and tiny PHP function that I’ve used on many projects to sanitize my input forms. As you are aware of, HTML forms are one source for injecting malicious code in programs to manipulate databases or traverse server directories. To make your programs much more secure, you’ll need to sanitize your inputs before doing anything, especially when dealing with databases. One function I’ve used repeatedly in my scripts is called sanitize(). Here’s the code:

The Code

// Sanitize input
function sanitize($in) {
 return addslashes(htmlspecialchars(strip_tags(trim($in))));
}

The addslashes function returns a string with backslashes to single quote (‘), double quote (“), backslash (\) and NUL (the NULL byte). This is particularly helpful when escaping special characters when dealing with database queries. The htmlspecialchars function converts special characters to HTML entities. For example & (ampersand) becomes &amp; and ‘”‘ (double quote) becomes &quot. This function prevents user-supplied text from containing unintended HTML markup.

The strip_tags function strips HTML and PHP tags from a string. It suppresses unwanted HTML markups from being displayed and prevents malicious PHP code from being executed. The trim function strips white space from the beginning and end of a string. For example, the string ” apple ” with white spaces will become “apple” without white spaces when the trim function is applied.

Usage

You can use the sanitize function to clean up the $_GET, $_POST, $_REQUEST and $_COOKIE input variables. In this example, we will use the sanitize function to clean up the form input called $_POST[‘name’].

$name = sanitize($_POST['name']);

Database Use

Before you can query, insert or update the database, you can use mysql_real_escape_string to escape special characters within your SQL statement to prevent SQL injections.

$name = sanitize($_POST['name']);
$name = mysql_real_escape_string($name);

There you have it. Two short and deliciously simple functions to sanitize your input and prevent malicious code from wrecking your programs. Let me know what you think.

Validate Email Addresses

Here’s one way to validate email addresses using the regular expression I found online that works great for me. You can use this little piece of PHP code in your forms or just about any place you need it. The regular expression should be typed in one continuous line, but I added a couple of line breaks for legibility purposes, in this example. You can also place this code  inside a function, so you can use it repeatedly by simply calling the function, in this case, validate_email(). If you have a better regular expression for validating email addresses, please share.

The Code

if (!eregi("
  ^[_a-z0-9-]+(\.[_a-z0-9-]+)*
  @[a-z0-9-]+(\.[a-z0-9-]+)*
  (\.[a-z]{2,3})$", $email)):
 echo "Invalid email.";
else:
 echo "Valid Email.";
endif;

The Function

function validate_email($email) {
 if (!eregi("
   ^[_a-z0-9-]+(\.[_a-z0-9-]+)*
   @[a-z0-9-]+(\.[a-z0-9-]+)*
   (\.[a-z]{2,3})$", $email)):
  echo "Invalid email.";
 else:
  echo "Valid Email.";
 endif;
}

A Great HTML5 Resource

There are hundreds of HTML5 resources on the Internet. One of my favorite is Dive Into HTML5. If you want an excellent introduction to HTML5, this is a good place to start. It’s written by Mark Pilgrim where he dissects all facets of HTML5 into ten chapters.

He starts out with a brief history of HTML, followed by how to detect HTML5, the details of the head elements, the markup, canvas, video, geolocation, local storage, offline applications and forms. The website also includes an Appendix of HTML5 elements.

This is an excellent read for those wanting to jump in and learn HTML5 quickly. If you want a hard copy, I recommend two books. One book is by Mark Pilgrim’s called, “HTML5: Up and Running.” The other is a book by Bruce Lawson and Remy Sharp’s called, “Introducing HTML5.”

Password and Text Boxes Are Not Of Equal Length

Why is the password field smaller than the input field in Internet Explorer 8? It’s the same in previous versions of the browser? I was recently working on a project that required authentication. I styled the login page. Everything looked wonderful. Perfect as a matter of fact, until I opened IE8. Wicked ugly. My main gripe really is, why is the password field smaller than the input fields?

I did a quick search online and found a solution.

You can style the input field to a certain width, like in this example.

input { width:12em; }

I’m using em instead px, because it’s probably more accurate.

But, styling the input field, like the one above, will make changes to every input field on the site. So, the quick and dirty way to style a login page, is to use inline CSS. In this example, we will use two input fields of text and passwords with inline styling.

<form>
<input type=’text’ name=’username’ style=’width:12em’ />
<input type=’password’ name=’password’ style=’width:12em’ />
</form>

So, there you have it. A quick and dirty solution to the uneven password and text input fields in Internet Explorer 8. If you have any other solutions, please let me know. I’ll be happy to hear about it.