Making CheckBoxList Play Nice With JavaScript

I’m working on a web page that allows the user to apply a variety of filters to a set of data. The old implementation involved a check box for each filter and then a ListBox with MultipleSelection set to true. The user would tick what ever filter they wanted to include and then select the items out of the ListBox. Every time the user makes a selection in one of the ListBoxes, we’re making an AJAX call to update the current filters. That works great but the user has to do two things, first tell us that they want to use a particular filter using the appropriate CheckBox and then select items out of the ListBox, sometimes holding down the Shift or Control key to do multiple selection.

We decided to change that to a CheckBoxList for each filter. This removes one step and makes the UI a little more fluid. However, it did cause one problem. Previously, the ListBoxes were being loaded with data on PageLoad by just adding a new ListItem for each piece of data. This works well because the ListItem can hold whatever value you want to key off of. However, a CheckBoxList renders as a table of CheckBoxes, none of which have the ability to hold a piece of data to key off of.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            for(int x = 0; x < 3; x++)
            {
                MyListBox.Items.Add(new ListItem("my value is " + x, x.ToString()));
            }
        }
    }

That code rendered a ListBox that had source like this:


From there, it was really easy to grab the value of any selections via JavaScript. Unfortunately, as mentioned above, the CheckBoxList does not render that way. Using the same code in the PageLoad ends up rendering this HTML:

As you can see, none of the checkboxes have the value attribute. There is now a label for each one but it has the Key of the ListItem and not the Value which isn't particularly helpful when you want to display one piece of data for the user but process another one based on their selection. What to do?

As it turns out, you can add an attribute that gets rendered as a span around both the input and label elements. In JavaScript, you can then grab an array of the inputs and an array of the span elements. When one of the input boxes is found to be checked, you can get the corresponding span element's attribute and use it. It looks a little something like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            for(int x = 0; x < 3; x++)
            {
                ListItem li = new ListItem {Text = "my value is " + x, Value = x.ToString()};
                li.Attributes.Add("myspecialid", x.ToString());
                MyCheckBoxList.Items.Add(li);
            }
        }
    }

When the items are loaded into the ListItems, we add an attribute called "myspecialid". It can be anything you want though it doesn't work if you pick a known attribute like id or value. Once that's done, the HTML renders like this:

Our new attribute has been included in a span tag around the input element and the value we want to track is included there. Now in JavaScript, we can do this:

function DoSomething() {
    var tableBody = document.getElementById("Tabstrip1_StudentsTab_MyCheckBoxList");
    var inputArray = tableBody.getElementsByTagName("input");
    var spanArray = tableBody.getElementsByTagName("span");
    for (var x = 0; x < inputArray.length; x++) {
        if (inputArray[x].checked) {
            alert("The id I want is " + spanArray[x].getAttribute("myspecialid"));
        }
    }
    if (groupsSelected.length > 0) {
        __aspx.HandleMonitorGroupFilter(groupsSelected);
    }
}

We grab all the input and span elements in the table. Then when we find a checkbox that is checked, we can grab the attribute we're interested in off of the appropriate span element using the getAttribute method. This is slightly hackish in that the two arrays of elements have to be in the same order but that seems like a reasonably safe assumption to make.

Overall, it seems like a good way to make the UI more fluid while still retaining the ability to manipulate necessary data on the AJAX calls.

Tags: , ,

No Comments

Google and Internet Explorer

Yesterday, the Gmail guys announced an improvement to Gmail related to popping windows out which makes multitasking easier. This is a pretty cool feature, one I think I subconsciously knew existed but never used. I run into this all the time when I’m writing a new message. Typically, I have to add more recipients but I can’t remember their emails and the autocomplete isn’t helping. Also, I search my email a lot while writing a new message and before I’ve always had to save to draft, go search, then go back to the draft. PITA. So this feature is muy cool. The whole reason for the post is that they have sped up the new window creation considerably. This is also muy cool.

What does this have to do with Internet Explorer? From the post:

Unfortunately, we weren’t able to make this work in Internet Explorer, so to see the speed-up, you’ll need to be using Mozilla Firefox, Apple’s Safari, or Google Chrome.

Not to go all conspiracy theorist on your ass but how hard do you think they really tried? Can’t you just see the engineers sitting around the conference table discussing this when Bob says “Wouldn’t it be cool if we just didn’t implement this for IE?” I just find it hard to believe that the geniuses at Google couldn’t come up with a way to make this work in IE. Maybe there really are some technological limitations that my puny brain can’t possibly handle but it’s a way better story if they just didn’t bother to try. Not that I’m complaining, I’d barely use IE if it was the last browser on earth after a nuclear holocaust.

Tags: , ,

No Comments

Learning MySql 45 Minutes at a Time

This and all future MySql posts are really for my own record keeping so that when dumb things happen that take me 45 minutes to fix, I have a record of them for future such incidents.

Today, for some reason, I couldn’t log in remotely to the MySql instance running on my Mac. This has been working just fine for the past month so needless to say, I had no idea what happened. As it turned out, the IP address of my Parallels instance had changed, rendering all the entries in my user table pointless. I had to update the user table with the new IP, restart the MySql instance and boom, up and running again.

USE mysql; 

select Host, User from user;

update user Set Host = 'NEW IP' where Host = 'OLD IP';

select Host, User from user;

Tags: ,

No Comments

For The Obsessive-Compulsive Amongst You

I hate it when the HTML in Visual Studio gets badly formatted. There have been nights when I have laid awake cursing badly formatted HTML in Visual Studio. But no more! There is hope for those of us whose OCD tendencies threaten to take over our brain and make do terrible things to less attentive people. Here’s how you can fix your badly formatted HTML in one step.

Go to Tools->Options->Text Editor->HTML->Miscellaneous and check the “Format HTML on paste” box. Close, copy and paste any offending HTML and what do you know, it’s correctly formatted.

Now I’m off to count the steps to the bathroom. Again.

Tags: , ,

1 Comment

StackOverflow Podcast #81 Notes from the Underground

So I’ve been listening to several podcasts on my commute these days and one that I religiously listen to is StackOverflow’s. Unlike other excellent podcasts like Boagworld and Herding Code, StackOverflow’s regularly makes me yell at my radio. I think I listen to this podcast for the same reasons I used to hang out in the AOL Christian chatrooms way back when I found the internet, i.e. the need to feel superior. How I can feel superior to people who have a very successful business and reputation in the tech world when I have a blog that averages 3 visitors a day is probably a discussion best left to my psychiatrist.

That said, on this week’s podcast (which I haven’t listened to fully thus supremely qualifying me to talk about it on the internet), Jeff Atwood starts off the podcast trying to explain away his GitHub comments. His main argument seems to boil down to him being a more command-and-control project manager. However, not 15 minutes later in the podcast, he essentially scolds Joel for running his business with a brick wall around it and not being open to outside information. Hello Pot, I’m Kettle. Seriously, if you’re so freaked out by the fact that you stuck some code up on GitHub, essentially abandoned it and then came back to find out other people had cloned it, you shouldn’t be calling someone out in public about their desire to build brick walls around anything. Further making this worse, Joel runs his own damn business and should have every right to build a brick wall around it if he wants to. But expecting to have a command-and-control approach to an open source site hosted on GitHub whose tagline is “Social Coding” is so illogical it boggles the mind.

The real problem here is that Jeff just doesn’t understand GitHub and went ahead and negatively commented on it on a very public, very popular podcast. And now he’s trying to say that he didn’t mean to piss anyone off, all the time sounding horribly condescending when he complains about features of GitHub THAT ARE INTENTIONAL.

Sigh. I’m going to have to start listening to this podcast on Mondays. The reaction I find myself having is much more suited to that day than Friday.

Tags: ,

No Comments

JsTestDriver First Impressions

I’m currently trying to get some unit tests written around a bunch of JavaScript code and I’m using JsTestDriver to do it. So far, I’m pretty impressed though there are some little gotchas here and there. It’s been a really good framework for basic testing assuming you aren’t doing a ton of work with other libraries like Prototype.js and script.aculo.us which of course I am. I’m sure there are ways around it but it’s going to take some digging to figure out what they are.

One minor thing that has been different for me from the documentation is that when I try to run tests, I need to specify the server explicitly on the command line even though I have a server running and a browser captured. The documentation says you can do this:

java -jar JsTestDriver.jar --tests all

.

However, I’ve found that I need to do:

java -jar JsTestDriver.jar --tests all --server http://localhost:9876

Where the server value may be different according to what server you started up.

Now I’m off to figure out how I can mock some of the Prototype.js dependencies.

Tags: , ,

No Comments

God Wrote In Lisp

This has been around a long time but I just heard it today. Text is here and audio is here. Very amusing.

No Comments

Successful Configuration Management Using Git

I am just beginning to play around with Git and so far I’m pretty happy with it. One thing I love about it is that the concept of branching is just part of the model. Branching is critical to successful software configuration management (SCM) and it’s a topic that strikes fear into the heart of any developer who has never done it. The idea of having all these branches that you have to eventually merge and bugs to fix and AAAAHHHHHHH!

Sigh. Of course this comes from the fact that most of our SCM tools have been craptacular at dealing with branches and merging. This craptacularness is built in to most of them because of the centralized server concept (though Perforce is spectacular, the opposite of craptacular, at branching and merging). On top of that, most Microsoft developers first and often only exposure to SCM is SourceSafe which is like driving a Pinto for your entire life. SCM in a robust environment is necessarily complex but it doesn’t have to be impossible and using the right tools changes the game. The new distributed source control tools like Git and Mercurial (which I have a soft spot for since it’s written in Python) are the future of decent development practices.

All this comes from reading a great article detailing how to use Git successfully to manage software development. The author details exactly how his team has been using Git to successfully branch and manage software changes. I haven’t begun to need all the ideas that his team is using but I hope to one day. Plus I thought my audience of 4 might find it useful.

Tags: ,

2 Comments

Making It Easy To Learn Programming

Glenn Reynolds talks about a shortage of geeks and one of his readers comments that a key contribution to this is when computers stopped shipping with BASIC. Glenn makes the plea to computer makers to include BASIC on the computers as a public service. Of course, Macs already ship with both Python and Ruby, surely superior languages to BASIC and excellent learning languages as well.

On a Mac, all you have to do is fire up a terminal (Apple Key + Space Bar and then type “Terminal”), type “python” in the new terminal and you have a place to start learning programming. Work through the Python tutorial and you’re well on the way to becoming a novice Python programmer.

Of course, on a Windows machine you’re going to have to do a little more work because, well, it is Windows after all.

Tags: ,

2 Comments

In Search Of Greater Productivity

So I finally broke down and installed ViEmu, a VI emulator for Visual Studio. Matt has been using it for quite awhile and seems happy with it. I’ve been slowly trying to improve my Vim skillz every week, working through the cheatsheet at ViEmu above, learning 5-10 new commands every couple of weeks (yay for Shift-A, so much better than i-Right Arrow key).

I have no idea how good I’ll get at it but since I’m in Visual Studio all day long, surely my productivity will start to increase.

Tags: , ,

No Comments