Hi
I have an HTML select element in my page and it's multiple property is
disabled (one item at a time mode) but I still want to transfer all the
items in the select to the server when the form is submitted.
I'm using javascript to change the multiple property of the select
element to true and then I'm looping through each option to change its
selected property to true.
Here is the code that's executed just before the form is submitted:
var selectElement = document.getElementById("mySelectElement");
selectElement.multiple = true;
for (var n = 0; n < selectElement.options.length; n++)
{
selectElement.options[n].selected = true;
}
document.forms[0].submit();
PROBLEM....
The browser is too slow in updating the renedered DOM select element on
the page from multiple=false to multiple=true. This causes the looping
code not to work correctly resulting in only the final option being
selected (which is what I'd expect if the select element were in
single-mode). You can verify this is a speed issue by inserting an
alert() between selectElement.multiple = true and the for loop. This
gives the browser enough time to update the page element so that the
every option is selected.
SOLUTION....
Even the slighest delay between the execution of selectElement.multiple
= true and the for loop will allow enough time for the browser to
update the select element, allowing each option to be sucessfully
selected in the loop:
functionA()
{
var selectElement = document.getElementById("mySelectElement");
selectElement.multiple = true;
setTimeout("functionB()", 1);
}
functionB()
{
var selectElement = document.getElementById("mySelectElement");
for (var n = 0; n < selectElement.options.length; n++)
{
selectElement.options[n].selected = true;
}
document.forms[0].submit();
}
Only tested this on IE6.
Anyone else come accross this before? Are there any more elegant
solutions to the problem? Any other thoughts?
Cheers
Rob