Archive for July, 2008

7/3/2008: 4:31 pm: RobertMac, Soccer

Not realizing there was a surfeit of newline characters in a largish mysqldump file I was analyzing, I tried to open it in TextMate. After a few minutes of listening to the hard drive in my Mac thrash away, I had to kill TextMate. One obvious solution was to split it into multiple lines, but obviously I couldn’t use TextMate for that.

Fortunately, the Unix utility sed is a great tool for problems like this. My file had the character string “\n” between all the parts that were reasonable to split into separate lines. The following command did the trick:

$ cat source.txt | sed 's:\\n:\
:g' > dest.txt

First, I used the cat utility to pipe the contents of source.txt into sed. Then, I used the substitute command to replace \n (the extra backslash is needed to escape the special treatment of backslashes) with a carriage return. The \ at the end of the first line escapes the literal new line character that causes the shell to go to the next line. The g tells sed to make this substitute globally throughout the file. I then redirected the output into dest.txt.

Sweet, sweet, Unix.

7/1/2008: 5:04 pm: RobertJavascript

It seems pretty simple, but still far too many web sites don’t set the focus on the input field that users are most likely to type into when loading a page.

Let’s say you have a page with an HTML form with the ID login with fields named user and password. Here’s the HTML and JavaScript for setting the focus to the user field on page load. IE lets you get away with being a bit sloppy and not properly referencing the HTML form element, but the code below works on Firefox, Safari, and other standards-compliant browsers.

<html>
<head>
<title>Focus Test</title>
  <script>
    function setFocus() {
      var loginForm = document.getElementById("login");
      if (loginForm) {
        loginForm["user"].focus();
      }
    }
  </script>
</head>
<body onload="setFocus();">
  <form id="login" method="post" action="">
    <table>
      <tr>
        <td><div align="left">User Name:</div></td>
        <td><div align="left"><input name="user" type="text"
            size="30" maxlength="30" tabindex="1" /></div></td>
      </tr>
      <tr>
        <td><div align="left">Password:</div></td>
        <td><div align="left"><input name="password" type="password"
            size="30" maxlength="50" tabindex="2" /></div></td>
      </tr>
  </form>
</body>
</html>

You can prove to yourself it works here.

Of course, there are lots of slight variants on this. You could give the field an ID and set the focus directly on it without getting the form first.