A simple method for preventing input field submission on enter key using jQuery

I recently worked on an application that had a form with a lookup feature in it. The form consisted of several dynamically added sections, each with a simple input field and a Find button. When the Find button is pressed, an AJAX call was made to load the data beneath the input field.

This was all working well except one thing: users kept typing in the Find field and hitting the Enter key, causing the form’s default action, Submit, to occur. After observing my tester make this mistake 5 times in a row, it was pretty obvious to me this was a UI design flaw and needed to be corrected.

Here is a very stripped-down version of the form, which basically does nothing, but shows the inherent problem with the design:

<html>
	<head>
		<title>Textbox Search Default</title>
		<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
		<script language="javascript">
			$(document).ready(function() {
				$('#btnFind').click(function() {
					// Do some logic to make an AJAX call and load the employee's info
				});
			});
		</script>
	</head>
	<body>
		<p>
			This sample form has a find field that we don't want to cause
			a different action on "enter" than the standard form submission.
		</p>
		<form>
			<table>
				<tr>
					<td colspan="2">
						<input type="text" name="employeeId" id="employeeId" />
						<input type="button" name="btnFind" id="btnFind" value="Find" />
					</td>
				</tr>
				<tr>
					<td>Name: <input type="text" name="employeeName" id="employeeName" /></td>
					<td>Location: <input type="text" name="location" id="location" /></td>
				</tr>
			</table>
			<input type="submit" value="Submit" />
		</form>
	</body>
</html>

As you can see, its a pretty simple example. There is a simple form, consisting of a table of values. The employeeId input field is filled out, the user presses “Find”, and the Name and Location is retrieved via an AJAX call and the input fields are pre-populated (you will have to imagine the second part, as the jQuery code above glosses over this part of the implementation).

The problem, again, is that if you type in an Employee ID and press Enter, you just submitted a blank form.

To solve this problem is rather simple. Here is an updated version of the HTML with the correction applied:

<html>
	<head>
		<title>Textbox Search Default</title>
		<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
		<script language="javascript">
			$(document).ready(function() {
				$('#btnFind').click(function() {
					// Do some logic to make an AJAX call and load the employee's info
				});

				$('#employeeId').keydown(function(event) {
					var key = event.keyCode || event.which;
					if(key == 13) {
						event.preventDefault();
						$(this).siblings('#btnFind').click();
					}
				});
			});
		</script>
	</head>
	<body>
		<p>
			This sample form has a find field that we don't want to cause
			a different action on "enter" than the standard form submission.
		</p>
		<form>
			<table>
				<tr>
					<td colspan="2">
						<input type="text" name="employeeId" id="employeeId" />
						<input type="button" name="btnFind" id="btnFind" value="Find" />
					</td>
				</tr>
				<tr>
					<td>Name: <input type="text" name="employeeName" id="employeeName" /></td>
					<td>Location: <input type="text" name="location" id="location" /></td>
				</tr>
			</table>
			<input type="submit" value="Submit" />
		</form>
	</body>
</html>

What is happening here is that we are adding a “keydown” event handler to the employeeId field which tests if the key being pressed is the Enter key (key #13). If it is, we simply call event.preventDefault(), which causes the event to not get propegated to the Form to trigger the submission, then generate a click() event on the Find button.

I think this is a pretty simple solution to the problem, and allows for a much better user experience.

Properties on JSTL’s forEach varStatus

I always forget what properties are available on the JSTL forEach’s varStatus. Here is a nice table listing whats available:

Property Getter Description
current getCurrent() The item (from the collection) for the current round of iteration
index getIndex() The zero-based index for the current round of iteration
count getCount() The one-based count for the current round of iteration
first isFirst() Flag indicating whether the current round is the first pass through the iteration
last isLast() Flag indicating whether the current round is the last pass through the iteration
begin getBegin() The value of the begin attribute
end getEnd() The value of the end attribute
step getStep() The value of the step attribute

For the record, I liberated this from here

Using jQuery UI Dialog without pre-defining

jQuery UI provides a handful of great components. One that I use a lot, both professionally and in my personal prjects, is the Dialog component.

Typically, the way you use the Dialog is by pre-defining a block, usually a DIV, and applying the dialog via a selector. For example:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
    <script>
      $().ready(function() {
        $('#dialog').dialog({
          modal: true,
          buttons: {
            Ok: function() {
              $(this).dialog("close");
              }
          }
        });
      });
    </script>
  <head>
  <body>
    <div id="dialog" title="My Dialog">
      <p>This is my wonderful dialog!</p>
    </div>

    <p>
      Some body text...
    </p>
  </body>
</html>

Here I am creating a small Dialog using a DIV element defined in the body. All of the samples on the jQuery UI page follow this same pattern.

The problem lies in the fact the dialog is defined as DIV elements directly in the body of the page. When the page loads, there will be a split second where the Dialog will be visible prior to jQuery running the ready() code. Further more, if the user has JavaScript disabled in their browser, or if they are simply running a browser that doesn’t support JavaScript at all, they will see the dialog in the body plain as day.

There are several workarounds. One would be to set the visibility of the dialog to hidden. This, again, assumes that the user’s broswer supports that. Another approach is to define the dialog completely in jQuery.

To do the latter is simple, and relies on the fact you can easily create DOM nodes using jQuery directly:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
    <script>
      $().ready(function() {
        $("<div title='My Dialog'><p>This is my wonderful dialog!</p></div>").dialog({
          modal: true,
          buttons: {
            Ok: function() {
              $(this).dialog("close");
              }
          }
        });
      });
    </script>
  <head>
  <body>
    <p>
      Some body text...
    </p>
  </body>
</html>

In this example, I am creating the exact same dialog. However, instead of it using a DIV element defined in the body as before, we create the DIV on the fly. Any HTML you put in the $(“”) will be created, and it can be as complex as you need. Obviously, the more complicated your Dialog, the harder it is to use this method, but for simple dialogs it works great.

The realities of going back into an office

Recently I was laid off after almost 14 years of employ, most of which I was a 100% telecommuter. The transition has been tough, but it is possible to make the transition if you understand these few realities:

You will NOT have as much time to handle non-work related tasks
When I was telecommuting, it was easy to take a 10 minute break to go answer some personal emails, BS with a friend of Skype, or even work on some side projects in your down time. It was nothing for me to take a quick 10 minute break to go unload the dishes or fold some laundry. In an office setting, however, these sorts of tasks are usually frowned upon (who wants to see you folding your skiveys?). Even simple tasks like making an appointment to drop your car off makes you look like you are wasting your productivity at the office. You must simply come to grasps with the fact that these things will have to be done on your own time, and not on the companies’. My solution is to use my drive time to make any personal phone calls needed, use Skype on my phone to keep up with my buddys, and schedule time late at night and on the weekend to work on side projects.

You will NOT see your family as much
One of the things I loved the most about telecommuting was that I got to see my kids quite a bit. I was home when they left for school and home when they got back. I was around when they were out of school, even when I had to work. I was constantly interacting with my kids all day long, and I loved it. Once you are working in an office, it’s tough to get quality time when you are getting home at 6, eating dinner, getting homework done, and then having only minutes of time before their bedtime.

How do I cope? Simple: I give up some of my personal time. A very wise person once told me “You will make time for the things you find are important”. So, if your family is one of those “important” things, then you need to set time aside for them. This means a lot less spur-of-the-moment interactions and a lot more planned events. You may even come to find that these interactions become even more special since they are harder to come by.

You will spend a LOT more time in the car
I think this is obvious, but when you go from a 0-minute commute to not-a-0-minute commute, you will spend more time going to and from work. One solution might be to carpool. Or, perhaps you could find some public transportation. Either of these solutions provide you a nice block of time to work on things while traveling.

In my case, my new job was about 40 minutes away, and no one I live near works in the same area. As I stated before, I tend to use this time to make phone calls or plan things, as long as those tasks don’t distract my driving.

You will be spending a LOT more time getting ready for work
Most days while telecommuting was spent in my basketball shorts, and if my wife was lucky, a t-shirt. Plus, it was easy to pour a bowl of cereal and eat at my desk while I started getting caught up on emails. Working in an office usually means showering at minimal, and in most cases getting dressed in some company approved business attire. This takes time, and must be factored into the “commute” time in the morning.

You WILL be spending a LOT more money
Most people who have never telecommuted have not experienced how much one can save by doing so. There are the obvious expenses, like gas, but there are a whole slew of non-direct expenses that most people don’t think about. Lunch, for instance, goes from eating what you have to going out in many cases, and there are all the expenses like clothes, both purchasing and in my case dry cleaning, and wear-and-tear on your car. All these little expenses add up. So, if you are doing a voluntary transition from telecommuting, make sure you have taken into account all the expenses you will have to absorb into your budget.

Working late hours means sacrificing A LOT more
When I was telecommuting, I had my “normal” office hours set from 6:30am to 5:30pm. This seems like a long day, but keep in mind I could take frequent breaks, and I had no commute time. It was easy to maintain long hours of availability at work but still have a life outside of work. Moving to the office, however, has shown me how tough it is to work late hours. Suddenly, working 6:30am to 5:30pm means waking up at 4:50am to leave by 5:50am and not getting home until 6:10pm. Your 11hr day just became almost 14hrs, a lot of which you didn’t even spend “working”.

So, is it all bad?
No, not really. For starters, telecommuting tends you make you feel like a shut-in. I was constantly wanting to get out of the house, even if it were just a quick trip to the store. Working in an office has made me greater appreciate simply staying at home. Also, working in an office allows you to bond better with your co-workers. Its hard to grab a bite with your coworker when they live in California and you live in Florida. I worked years with some of my ex-coworkers and never knew what they even looked like. But, that said, I would STILL pick a telecommuting job over a commuting job any day.