as*@asd.com wrote:
I need to find the value/index of the previously selected item of a
select list. That is, when the user selects an item from the list and
a certain condition elsewhere in the form is not met, I need to
display an alert box warning the user that a selection cannot be made,
and redisplay the item that was previously selected. What is the most
efficient way of doing this?
Please email replies to td***@perfectsolve.com
Here is a posted solution:
Create a global array when the page is loaded. When the user selects
each selection, put the selected item index into the array using
push().
If the current selection fails your test, pop the last item off the end
of the array, the new last item in the array will be the index of the
previous selection. You can keep poping the last one off until there
are none left - at this point, reset the form.
If you only want to remember the last one and not all the previous
ones, then just set a single variable and replace it with each
successive successful selection.
Cheers, Rob.
<script type="text/javascript">
// Global array to store selection indexes
selectedItems = new Array();
// Adds current selection index to array
function addCurrent(a){
var x = a.options;
for (var i=0;i<x.length; i++) {
if (x[i].selected) {
selectedItems.push(i);
}
}
}
function selectLast(a) {
var x = a.options;
if (selectedItems.length <= 1) {
// alert is optional
alert('No previous selection, resetting list');
// clear array and reset form
selectedItems.pop();
a.parentNode.reset();
} else {
// clear last item from array, set selected to
// new last item (previous index)
selectedItems.pop();
var p = selectedItems[selectedItems.length-1];
a.options[p].selected = true;
}
}
</script>
<form action="" name="aForm"
onchange="addCurrent(this.optList1);">
<select name="optList1">
<option value="opt0">
<option value="opt1">Option 1
<option value="opt2">Option 2
<option value="opt3">Option 3
<option value="opt4">Option 4
</select>
<input type="button" value="Back to previous"
onclick="selectLast(this.form.optList1);">
<input type="reset">
</form>