I'm trying to move the options of one select list to another select list. The "source" select list is divided into optgroups, and the "target" select list is not. I want to somehow keep track of the moved option's optgroup, so that if I remove it from the "target" select list, it moves back into it's respective optgroup in the "source" select list.
I have things moving back and forth, but I'm not sure how to handle the optgroup tracking. Here's basically what I have:
Expand|Select|Wrap|Line Numbers
- <script language="JavaScript" type="text/javascript">
- function MoveOption(objSourceElement, objTargetElement)
- {
- var aryTempSourceOptions = new Array();
- var x = 0;
- //looping through source element to find selected options
- for (var i = 0; i < objSourceElement.length; i++) {
- if (objSourceElement.options[i].selected) {
- //need to move this option to target element
- var intTargetLen = objTargetElement.length++;
- objTargetElement.options[intTargetLen].text = objSourceElement.options[i].text;
- objTargetElement.options[intTargetLen].value = objSourceElement.options[i].value;
- }
- else {
- //storing options that stay to recreate select element
- var objTempValues = new Object();
- objTempValues.text = objSourceElement.options[i].text;
- objTempValues.value = objSourceElement.options[i].value;
- aryTempSourceOptions[x] = objTempValues;
- x++;
- }
- }
- //resetting length of source
- objSourceElement.length = aryTempSourceOptions.length;
- //looping through temp array to recreate source select element
- for (var i = 0; i < aryTempSourceOptions.length; i++) {
- objSourceElement.options[i].text = aryTempSourceOptions[i].text;
- objSourceElement.options[i].value = aryTempSourceOptions[i].value;
- objSourceElement.options[i].selected = false;
- }
- }
Expand|Select|Wrap|Line Numbers
- <table><tr><td>
- <select name="Enabled1" id="Enabled1" size="20" multiple
- style="width: 300px;">
- <optgroup label="Option Group 1">
- <option value="Value1">Option1</option>
- <option value="Value2">Option2</option>
- </optgroup>
- </select>
- </td><td>
- <input type="button" name="add" value=" add -> " style="width: 100px;"
- onclick="MoveOption(this.form.Enabled1, this.form.Disabled1)"><br />
- <input type="button" name="remove" value=" <- remove " style="width: 100px;"
- onclick="MoveOption(this.form.Disabled1, this.form.Enabled1.)">
- </td>
- <td>
- <select name="Disabled1" id="Disabled1" size="20" multiple style="width: 300px;">
- </select>
- </td></tr></table>