Select part of the text in a textbox with javascript

There was a brief discussion on the Tracks mailing list over the way its autocomplete works (the project uses Scriptaculous’s nice Autocomplete widget in local mode): should it automatically fill in the entire word once enough text is entered to match one of the choices (annoying if you have to backspace because the guess was wrong) or make you hit tab or enter to fill in the suggestion. To make a long story short, I suggested a third approach – fill in the remainder of the match selected, so if its wrong, the user can type over it, like this:

textpartialselect.png

This isn’t rocket science and has been done forever, but I didn’t find a single good reference on how to select just part of the text in a text box. Scriptaculous and prototype don’t support it at the present time, and like anything good in browser-land, there’s at least two different ways to skin this cat. The IE way, and everyone else’s way (actually I don’t know which way safari and opera work, but the code here does work for them too).

I saw one of the YUI widgets supported “typeahead” so I looked through its code to find the relevent javascript calls – for IE its “createTextRange” and for firefox its “setSelectionRange”. Combine those and you get the following, which I’ve tested as working on IE 6 (or was it 7?), Firefox (mac), opera (mac) and safari.

function selectSomeText(element,begin,end)
{
if (element.setSelectionRange)
{
element.setSelectionRange(begin,end);
}
else if (element.createTextRange)
{
var range = element.createTextRange();
range.moveStart("character",begin);
range.moveEnd("character",end);
range.select();
}
}

One of these days I’ll refactor the code I wrote to test this with scriptactulous and throw that up here as well.

Loading Flex from a Flash 8 swf; Actionscript-only version checking

Not too long ago, I was poking around the internets trying to figure out how to load an Actionscript 3 (Flex) SWF file from a Flash 8-compatible (AS2) swf after version checking the player to see if it is version 9 or greater. I managed to piece together what I needed and went on my merry way.

Yesterday someone who had seen my queries on the flexcoders mailing list wrote to me to ask if I had found an actionscript-only solution after all, so I will post the solution here for future reference. I certaintly couldn’t have come up with this without tidbits from here and there…

The key to this working is not loading anything onto the stage before running this code. In fact, in my solution, I use a flash project that only does version checking and loads SWFs externally for both cases where flex is supported and where it isn’t. Insert something like the following in the first frame of your timeline and you should be all set.

var FLEX_NOT_SUPPORTED_SWF ="absolute path to a flash 8 or below swf";
var FLEX_SUPPORTED_SWF = "absolute path to a flash 9 swf";
var versionInfo = getVersionInfo(); // use your favorite implementation of this
if (versionInfo.majorVersion >= 9)
{
loadMovieNum(FLEX_SUPPORTED_SWF,0);
}
else
{
loadMovieNum(FLEX_NOT_SUPPORTED_SWF,0);
}

Flex and REST don’t get along

I was a bit dismayed on Friday to find that Flex is severely crippled in the way it handles fault responses via the HTTPService component. In short, it doesn’t provide the response body if the HTTP status code indicates an error. It doesn’t even tell you the status code so you can create an intelligent error message. This is easy to do in javascript, so its lame to find that Flex and actionscript are actually less capable in this regard. I found another post describing this issue where blame is placed on the browser implementation.

I had planned to to return HTTP 404 plus an xml fragment containing the error message when a resource wasn’t found via a given id number, but now that’s out the window. Instead I’m always returning OK, and switching based on the body XML content. Oh well.

In order to do so, I needed to determine the root node of the xml – was it “error” or something else? Using e4x, navigating the dom is usually child’s play – just nodename.childname.text() for example. This is where I made a “rookie mistake” in not realizing that the XML object actually represents the root node, not some super-root. So I was testing for the existence of x.error (where x is the XML object, and error would be a first level child) rather than just checking the localname of the xml object, which in fact is the node named “error”. Maybe this will show up in google and help someone experiencing a similar brain-fart one day.

Apollo alpha available

I saw (via basement.org) that Adobe Apollo is available at adobe labs. It remains to be seen if the whole I need to install tens of targeted rich clients thing will take off (java web start, anyone?), but if it does, this looks like a great tool to be using.

When I was working at Lotus on Workplace Client, I often wondered if Java on the Eclipse platform was really the best way to deploy rich client applications. The only compelling things it had to offer over browser-based applications was an offline experience and desktop integration. (plus some hand waving about leveraging existing Java skills). Now that flex has a more traditional programming model around the flash runtime, and apollo provides desktop integration and offline support (with synchronization) as well as update/provisioning, the advantages of using the Eclipse platform with layers of overpriced IBM code piled on top are evaporating. One could still make a case for the lipstick on a legacy-code pig project (see Hanover/notes 8 ) building on the Java/eclipse stack, but I can’t see any reason why a company would invest in something like Lotus Expeditor for green-field development.

Id Checks

My naturalization ceremony was at a federal courthouse. They require two forms of identification to enter as a visitor, but its just a guard looking at it to see if them match each other and you. He’s not typing them into a computer to check against a “no-courthouse” list, so what security value does that provide? Seems pointless to me.

Citizen Kebinger

I became an American citizen today, just ten days short of nineteen years after moving here and about a year since applying. There were 98 other people from 30-something countries being naturalized as well. First we all stood in line to check in and give up our green cards (which went into an official looking Target bag), Then we waited more after being seated, during which we were told some rather hokey stories by a manager in the Immigration Services office and read and re-read our letters from the president (Dear fellow American…)

Once the judge arrived, things moved quickly- first we all said the oath together, then the judge made a nice speech. Due to the hokey stories and the fact that I wasn’t running away from religous persecution or civil strife, I expected to view things through my usual detached, ironic perspective, but once things got going, I found it quite moving.

After the judge was done speaking, a grade school daughter of one of the fresh citizens led us in the pledge of allegiance and that was it. We filed out a row at a time to collect our certificates of naturalization and that was that.

Here’s me before the ceremony, permanent resident card in hand:

beforenatphoto.jpg

And afterwards, government-issue mini flag in hand:

afternatphoto.jpg

Big difference eh?

Can’t share session contents between applications on Tomcat

I got stuck for a little while on this problem today – I was pushing some content into the session from a Flex app into one web app, and then trying to read it from another. It turns out this won’t work under tomcat. I thought at first it was because the cookie paths were different, so I added emptySessionPath=true to my server.xml file, but that actually doesn’t fix the problem. Thinking about it, it is perfectly reasonable that two web applications that aren’t associated in some way (as being in the same ear) can’t get at each others session information.
Lesson learned: either share state in some non-session mechanism (like the database) or move the resources into the same application.

We’re taking fire!

Kristi and I went to visit my parents today – it was a delayed visit for my father’s birthday, but I’d been sick. Anyways, I’m always amused when I drive through Hartford by the (relatively) new logo for Bradley Airport. To me, it looks like an airliner that is taking ground fire, being shot at by gi-joe style laser guns. Not the best imagery to evoke in this day and age.
bradley.png

Without insurance

I saw this disturbing story (via the wesabe blog) about a woman who can’t buy health insurance because she had a bout with cancer. Being without dental insurance bothers me enough, ( i still kick myself for not picking up the COBRA coverage before the deadline – the thought of paying for a root canal out of pocket gives me the shivers) but the thought of no health insurance is terrifying.

I can’t believe that we, as a country can’t solve this problem and make it easier for individuals to obtain insurance. By insuring everyone, even the young and relatively healthy, the risk is spread around enough that it is overall more affordable for everyone. Surely having portable insurance would allow people to start their own businesses or just take extended time off to do something different, which would have to be a boost to the economy. It seems like the anti-health care forces would have us believe that any insurance changes would be bad for small business, but I can’t believe that is truly the case if we do it right.

Recursive deletes

Posting this little ruby snippet so i can reference it later. Need to recursively delete directories with a certain name in a large tree? The simplest example is scrubbing those pesky .svn directories in a subversion repository, which can be done like so:

require ‘fileutils’
Dir.glob(“**/.svn/”) {|fname| FileUtils.rm_r(fname) }

another use case I have here at work is to scrub extra maven generated versions of code out of each java project (so as to keep eclipse sane). In this case, we want to delete all directories (and their contents) named “target” except for the target directory at the root (because mvn clean is “too clean” in this instance):

require ‘fileutils’
Dir.glob(“**/target/”) {|fname| FileUtils.rm_r(fname) unless /^target.*/ =~ fname}

It gets a bit more complicated if you want to exclude list of directories from the operation. Here I found Ruby’s Enumerable module detect method quite handy to short circuit evaluate all the directories to exclude regex on each directory.


require 'fileutils'
@exclude= [/^foo.*/ , /^bar.*/ , /^james.*/, /^target.*/]
Dir.glob("**/target/") do |fname|
@erase = @exclude.detect{ |r| r =~ fname }.nil?
if @erase
puts "erasing #{fname}"
FileUtils.rm_r(fname)
else
puts "skipping #{fname}"
end
end

Note: this code won’t copy and paste well because wordpress replaces quotes with smartquotes. I also really need to fix my stylesheet for code samples.