views:

44

answers:

2

I have a couple select elements:

<select name="empID" onchange='setSupervisor(this);'>
    <option value="111" sid="222">Eric Employee</option>
    ...
</select>

<select name="supervisorID">
    <option value="333">Susie Supervisor</option>
    <option value="222">Stan Supervisor</option>
</select>

And a javascript function:

function setSupervisor(sender)
{
    ??
}

How can I set the supervisor dropdown after the user selects from the employee dropdown? The tricky part here (at least to me) is having to use a custom sid and not the value from the employee dropdown.

A: 

Try this:

var empID = document.getElementsByName("empID").item(0);
var supervisorID = document.getElementsByName("supervisorID").item(0); //This becomes a bit easier if you set an ID as well as a name in your HTML    
var index = empID.selectedIndex;
var sid = empID.options[index].getAttribute("sid");
for(var i=0; i<supervisorID.options.length; i++)
{
    if(supervisorID.options[i].value == sid)
    {
        supervisorID.selectedIndex = i;
        break;
    }
} 
ristonj
Changing "int i" to "var i" and then alert(supervisorID.selectedIndex) is always 0 no matter who is selected as an employee.
mudface
I edited it, based on Tim Down's answer above. See if that works. If not, after setting the sid, insert alert(sid) to see what value it gets.
ristonj
A: 
function setSupervisor(sender) {
    var selectedOption = sender.getElementsByTagName("option")[sender.selectedIndex];
    var sid = selectedOption.getAttribute("sid");

    var supervisorSelect = document.getElementsByName("supervisorID")[0];
    for (var i = 0, len = supervisorSelect.options.length, option; i < len; ++i) {
        option = supervisorSelect.options[i];
        if (option.value == sid) {
            option.selected = true;
            return;
        }
    }
}
Tim Down
No error, but it doesn't set the supervisor select.
mudface
Really? Worked perfectly in all browsers I tested (Firefox 3.5.7, IE 7, Chrome) for me. I added one dummy option to the first select so that it had two options and hence the onchange could fire.
Tim Down
You are right, it does work. I had another type of issue. Thanks for the help!
mudface