A project recently came up at work which sounded like a good candidate for a web application, so I'm using it as a chance to do some real "hands on" work in ASP.NET MVC (rather than building off other people's good work on projects like FunnelWeb).
The first thing I wanted to try (and the topic of this blog post) was to disable some input controls based on the item selected in a drop-down list. Let's back up and set the scene:
This application is a simple "ordering" process so a farm can order feed for their silos. When the user clicks "new order" he's presented with a list of all his silos, and given a space where he can type in how many tonnes of feed he needs in each one. Here's a screenshot:
Pretty straight forward. I want the "quantity" and the "day" controls disabled when the user selects "(None)" from the product drop-down, since it's not valid to enter a quantity without actually ordering a product. I'm happy to leave the "comments" control enabled, though, in case the user wants to leave a comment with their order.
So I need to do two things when the page finishes loading: First, disable all the relevant controls for silos where "(None)" is already selected; and second, make sure that the controls are disabled and re-enabled when the user changes on and off the "(None)" product in the drop-down.
After a bit of reading, and some help from some seasoned web developers on Twitter, I came up with this little script which lives at the bottom of the page:
So the "toggleQuantity" function essentially looks for an input and select element in the same table row as the product drop-down, and changes them accordingly. It also clears any values assigned to those controls, so the user won't get confused by seeing a value in a disabled control.