Javascript how to use class instead of id for dropdown menu

I have had another question similar to this and have tried to see if I could make it work in a similar way but I have been unsuccessful. What I have is two drop down menus one of them has its options created depending on what one you select on the first dropdown menu but I have run into an issue that I need to use the same menu twice on the same page which I thought may have worked but it didn’t. I have realised on my own accord that it is because you can’t have two objects with the same id. I’m wondering how I would make the script below work with a class instead of id of the form?

var i;
function fill_damage(i){
    var form1 = document.getElementById("form1a");
    document.form1aa.damage.options.length=0;
    switch(i)
    {
        case 1:
            form1.damage.options[0] = 
                new Option('Cracked screen','Cracked screen');
            form1.damage.options[1] =
                new Option('Cracked top case','Cracked top case');
            form1.damage.options[2] =
                new Option('Cracked bottom case','Cracked bottom case');
            form1.damage.options[3] =
                new Option('Broken keyboard','Broken keyboard');
            form1.damage.options[4] =
                new Option('Faulty touch pad','Faulty touch pad');
            form1.damage.options[5] =
                new Option('Hinge broken','Hinge broken');
            form1.damage.options[6] =
                new Option('Motherboard','Motherboard');
            form1.damage.options[7] =
                new Option('Hard drive','Hard drive');
            break;
        case 2:
            form1.damage.options[0] =
                new Option('Re image','Re image');
            form1.damage.options[1] =
                new Option('Wireless cert','Wirless cert');
            form1.damage.options[2] =
                new Option('Application','Application');
            form1.damage.options[3] =
                new Option('Hacked','Hacked');
    }
}


<form name="form1aa" method="post" id="form1a" >
    <select name="type" 
        onChange="fill_damage(document.form1aa.type.selectedIndex);">
        <option value="">Select Type</option>
        <option value="Hardware">Hardware</option>
        <option value="Software">Software</option>
    </select> 
    <select name="damage">
        <option selected="selected">Select Type First</option>
    </select>
</form>

Answer

What you need is document.getElementsByClassName()

document.getElementsByClassName("yourClass")[0]; //first node with that class

Careful though as you can see here: http://www.quirksmode.org/dom/w3c_core.html#fivemethods, IE 7/8 does not implement this method. I would suggest to take a look at a framework like jquery to simplify all browsers compatibility headache!

Leave a Reply

Your email address will not be published. Required fields are marked *