Great Idea!

Ever have one of those moments where what seems like a brilliant idea falls very flat? I had one of those experiences yesterday where I had just not thought my stellar plan all the way through. In a lot of interactive websites, we have programmed in selection lists of some kind on most forms. Some of these have an ‘other’ option where you can write in the ‘other’. What this project in particular called for was having the other option actually make the other text field hide and show. It’s a very common thing to do, but of course I wanted to make it all super fancy. What I wanted to do was be able to have the selection list, which was populated by a database table, be able to automatically determine which one was the ‘other’ selection by the position in the list. I usually set up my selection lists in the database with the ID, text and a sort order so we know how to show the listing (alphabetical order rarely seems to be sufficient). So here I was thinking that brilliantly I could just set the Other selection to a sort order of 9999 which would generally put it as the last one in the list (after all, if you had 9998 choices, it’s not going to be in a drop down) and I can use that number to determine if there needs to be showing the other text box. So, that’s how I planned it. Well, when I actually got to working on it, duh, how do we know what that number is? The value of the select is going to be the ID, and the text is obviously the text, and there’s no other place to put it. Silly me. So instead I just read the text of the select using javascript and if it was ‘other’ then I would produce the other text box.

What I did for the javascript was create a standard function that checks all select lists upon the change event. Within that, it tests to see if the text is ‘other’, and if it is other, it fires off the function to show the hidden div that contains the other text box. The div is hidden during the document ready function (jQuery is being used) so if for some reason javascript is disabled, the other box is not hidden and the whole function can degrade nicely. What I did have an issue with was finding the text of the selected option value. Since I’m using a standard change event on all select lists, I have the ability to use the ‘this’ keyword. However, in most cases, jQuery examples are using the named element format so finding the right combination was a little more fun. Normally one can simply find the selected text like this: $(‘#myfield :selected’).text() but that doesn’t work with ‘this’. Once I figured that out, I just had to add in a div that I could hide and show. To make this fun and easy, the div id is simply the field id with a “DIV” prepended to it. It makes the selector easy.

if($(this).find(‘:selected’).text() == ‘Other’) //or $(this).children(“option:selected”).text() would work too