Forum Moderators: open

Message Too Old, No Replies

changing form field class via javascript

         

librarc

5:49 pm on May 22, 2007 (gmt 0)

10+ Year Member



I currently have a list box that when disbaled, has a class='a'from my css. The box is enabled when an item is chosen from a dropdown box within the same form. I would like to change the class of the box (class='b') when it is enabled, and back to class='a' when disabled. Can someone please advise on how I can use javascript to facilitate the change?

Fotiman

6:36 pm on May 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If you don't mind using a JavaScript library, here's how I'd do it (using the Yahoo UI Library [developer.yahoo.com]):

1. Include this in your head:


<script src="http://yui.yahooapis.com/2.2.2/build/yahoo-dom-event/yahoo-dom-event.js"></script>

Alternatively, download the library to your own server and use the locally hosted versions instead.

2. Assign your event listeners. You'll need to replace the ID's and/or class names with your actual ID's and/or class names:


<script type="text/javascript">
// When the window has finished loading, attach listener
YAHOO.util.Event.on(window, 'load', function() {
// Get the dropdown list that will control the enabled/disabled state
var dropDown = document.getElementById('yourDropDownId');
if( dropDown ) {
// Attach an event listener to the dropdown
YAHOO.util.Event.on(dropDown, 'change', function() {
// Get the listbox to be controlled
var listbox = document.getElementById('yourListBoxId');
if( listbox ) {
// Add your own case here to determine enabled/disabled state
var enabled = (this.selectedIndex!= 0);
// Swap the class
YAHOO.util.Dom.replaceClass(listbox,(enabled?'a':'b'),(enabled?'b':'a'));
}
});
}
});
</script>

Hope that helps.