treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Change class using select drop down menu

  • Hi there.

    I want to have a button displayed on the page and then using a select drop down menu with class names be able to have users select an option and dynamically change the look of that button by changing its class.

    I have seen examples with anchor tags on links but not with a select box.

    Any references or help would be greatly appreciated
  • This works.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>JS Change Class</title>
    <style type="text/css" media="screen">
    .red { border: 1px solid red; }
    .blue { border: 1px solid blue; }
    .green { border: 1px solid green; }
    </style>
    </head>

    <body>

    <select id="colors">
    <option value="red">Red</option>
    <option value="blue">Blue</option>
    <option value="green">Green</option>
    </select>

    <input type="button" class="red" value="This is a button" id="button" />

    <script type="text/javascript" charset="utf-8">

    var colors = document.getElementById('colors');
    var button = document.getElementById('button');

    addEvent(colors, 'change', function() {
    button.className = colors.value;
    });

    // Based on the lessons from Nettuts
    function addEvent(obj, evt, fn) {
    evt = evt.replace('on', '');
    if( obj.attachEvent )
    obj.attachEvent('on' + evt, fn);
    else
    obj.addEventListener(evt, fn, false);
    }

    </script>

    </body>
    </html>